删除 lapply 中的循环

标签 r

我有一个我想摆脱的循环,但我也不太明白怎么做。假设我有一个数据框:

tmp = data.frame(Gender = rep(c("Male", "Female"), each = 6), 
                 Ethnicity = rep(c("White", "Asian", "Other"), 4),
                 Score = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))

然后我想计算 Gender 和 Ethnicity 列中每个级别的平均值,这将给出:

$Female
[1] 9.5

$Male
[1] 3.5

$Asian
[1] 6.5

$Other
[1] 7.5

$White
[1] 5.5

这很容易做到,但我不想使用循环——我要追求速度。所以我目前有以下几点:

for(i in c("Gender", "Ethnicity"))
    print(lapply(split(tmp$Score, tmp[, i]), function(x) mean(x)))

显然,这使用了一个循环,这就是我卡住的地方。

很可能有一个函数已经做了我不知道的这种事情。我看过聚合,但我认为这不是我想要的。

最佳答案

你可以sapply()覆盖tmpnames,除了Score,然后使用by()(或aggregate()):

> sapply(setdiff(names(tmp),"Score"),function(xx)by(tmp$Score,tmp[,xx],mean))
$Gender
tmp[, xx]: Female
[1] 9.5
------------------------------------------------------------ 
tmp[, xx]: Male
[1] 3.5

$Ethnicity
tmp[, xx]: Asian
[1] 6.5
------------------------------------------------------------ 
tmp[, xx]: Other
[1] 7.5
------------------------------------------------------------ 
tmp[, xx]: White
[1] 5.5

但是,这在内部使用了一个循环,所以它不会加速很多......

关于删除 lapply 中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26019996/

相关文章:

r - 使用 ggplot2 和facet_wrap 绘制估计值,无需重新拟合模型

html - R : CSS defined in header is not working inside leafletProxy 的传单

r - 将一列包含确切信息的列拆分为两列

r - 有没有办法对不同长度的变量进行 wilcoxon 检验?

r - 如何将函数另存为新的 R 脚本?

r - 将 Sparklyr 的 <dbl [2]> 结果拆分为 Spark 对象

r - 如何从 terra SpatRaster 构造经度、纬度、值数据框

r - 在文本编辑器中集成 R linter 的选项有哪些? svTools、codetools 等中的 lint

c++ - 编译器错误 : Undefined symbols for architecture x86_6 when using Rccp classes.

r - 使用 Rcpp 通过引用传递 Armadillo 稀疏矩阵