首页 > 解决方案 > for循环按组计算平均值(也忽略NA)

问题描述

我想创建一个for loop

  1. 创建 a1, a2,...a10 作为组均值的变量
  2. 根据组变量计算变量 b1、b2、b3....b10 的平均值groupid
  3. 在计算平均值时忽略 NA,我使用了na.rm=TRUE
df <- within(df, {a1 = ave(as.numeric(as.character(b1)), groupid, FUN=function(x) mean(x, na.rm=TRUE))})  
df <- within(df, {a2 = ave(as.numeric(as.character(b2)), groupid, FUN=function(x) mean(x, na.rm=TRUE))})
.
.
.
df <- within(df, {a10 = ave(as.numeric(as.character(b10)), groupid, FUN=function(x) mean(x, na.rm=TRUE))})

我怎样才能将这 10 行愚蠢的代码改写成优雅的for loop

标签: rfor-loopgroup-byna

解决方案


也许可以尝试以下

df <- sapply(1:10, function(k) eval(parse(text = sprintf("within(df, {a%d = ave(as.numeric(as.character(b%d)), groupid, FUN=function(x) mean(x, na.rm=TRUE))})",k,k))))

推荐阅读