简体   繁体   English

R - 是否有有效的方法来执行此重复性任务?

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

Using R, I'm trying to create a column of mean with multiple columns as follows.使用 R,我正在尝试创建一个包含多个列的均值列,如下所示。 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)

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我们可以使用lapply从 1 到 5 的序列,使用seq创建从该值到 5 的序列, paste 'c',select 'df' 的列,应用rowMeans ,然后分配 ( <- ) output回到新专栏

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这可以通过grep完成

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM