【发布时间】:2020-03-27 02:48:16
【问题描述】:
我想创建一个for loop
- 创建a1,a2,...a10作为组均值的变量
- 根据组变量
groupid计算变量 b1、b2、b3....b10 的平均值 - 为了在计算平均值时忽略 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?
【问题讨论】: