R - are there efficient ways to perform this repetitive task?

Viewed 37

Using R, I'm trying to create a column of mean with multiple columns as follows. Are there any efficient way to perform this repetitive task?

df$c1mean = rowMeans(subset(df, select = c1_1:c1_5), na.rm = TRUE)
df$c2mean = rowMeans(subset(df, select = c2_1:c2_5), na.rm = TRUE)
df$c3mean = rowMeans(subset(df, select = c3_1:c3_5), na.rm = TRUE)
df$c4mean = rowMeans(subset(df, select = c4_1:c4_5), na.rm = TRUE)
df$c5mean = rowMeans(subset(df, select = c5_1:c5_5), na.rm = TRUE)
1 Answers

We can loop over the sequence from 1 to 5 with lapply, use seq to create the sequence from that value to 5, paste the 'c', select the columns of 'df', apply rowMeans, and assign (<-) the output back to new columns

df[paste0("c", 1:5, "mean")] <- lapply(1:5, function(i)  
            rowMeans(df[paste0("c", i, "_", i:5)], na.rm = TRUE))

This can be done with grep

nm1 <- paste0("c", 1:5)
df[paste0(nm1, "mean")] <- lapply(nm1, function(nm)
           rowMeans(df[grep(nm, names(df))], na.rm = TRUE))) 
Related