r - for循环按组计算平均值(也忽略NA)
问题描述
我想创建一个for loop
- 创建 a1, a2,...a10 作为组均值的变量
- 根据组变量计算变量 b1、b2、b3....b10 的平均值
groupid
- 在计算平均值时忽略 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
?
解决方案
也许可以尝试以下
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))))
推荐阅读
- beagle - 如何在 Beagle 中创建适用于 Angular、Android 和 iOS 的图像?
- laravel - Laravel saml2 元数据加密块
- c++ - 为什么数据验证只检查第一个条目?
- r - 在 R 中使用多个重复变量整理数据
- python - Plotting interpolation in python
- sql-server - SSMS - VARCHAR(MAX)可以在网格中显示的最大字符串大小是多少
- powershell - Powershell:将包含变量的字符串传递给函数
- python-3.x - zappa 正在打包在另一个目录中可用的额外文件
- python - if __name__ == "__main__" 如何转换为函数 main()?
- python - 热图上 FN 和 FP 之间的混淆矩阵混淆