在 R 中,遇到问题 'list' object cannot be coerced to type 'double' when using 'by' function

In the R, meet problem 'list' object cannot be coerced to type 'double' when using 'by' function

我试图使用 by 来获得数据的均值和标准差

这是我的代码

dstats <- function(x)(c(mean=mean(x),sd=sd(x)))

aggregate(mtcars[vars],by=list(am=mtcars$am), FUN = dstats) 

这很好用,我得到了

 am  mpg.mean    mpg.sd   hp.mean     hp.sd   wt.mean     wt.sd
1  0 17.147368  3.833966 160.26316  53.90820 3.7688947 0.7774001
2  1 24.392308  6.166504 126.84615  84.06232 2.4110000 0.6169816

为了得到整齐的图表,我想用mtcars$am分隔,我试过


by(mtcars[vars],mtcars$am, FUN=dstats)

然后我遇到了

Error during wrapup: 'list' object cannot be coerced to type 'double'

我不认为数字是data.frame是字符,因为我可以正确使用aggregate。 我想知道这是什么错误。谢谢。

by 在被 mtcars$am 分割的 data.frame 上工作,所以你的函数需要在 data.frame 而不是矢量上工作,所以下面的例子我使用 sapply 遍历每一列并计算平均值和标准差:

by(mtcars[vars],mtcars$am, FUN = function(u)sapply(u,dstats)) 
mtcars$am: 0
           mpg       hp        wt
mean 17.147368 160.2632 3.7688947
sd    3.833966  53.9082 0.7774001
------------------------------------------------------------ 
mtcars$am: 1
           mpg        hp        wt
mean 24.392308 126.84615 2.4110000
sd    6.166504  84.06232 0.6169816

返回与嵌套的聚合输出相同的格式并不容易 data.frame:

res = aggregate(mtcars[vars],by=list(am=mtcars$am), FUN = dstats)
class(res$hp)
[1] "matrix"
# to get mean hp for different groups, you have to do:
res$hp[,"mean"]
[1] 160.2632 126.8462

为了得到与 by 类似的东西,它更复杂一点:

res = do.call(rbind,
by(mtcars[vars],mtcars$am,function(i){
unlist(lapply(i,dstats))
})
)
res = data.frame(am=levels(factor(mtcars$am)),res)

  am mpg.mean   mpg.sd  hp.mean    hp.sd  wt.mean     wt.sd
0  0 17.14737 3.833966 160.2632 53.90820 3.768895 0.7774001
1  1 24.39231 6.166504 126.8462 84.06232 2.411000 0.6169816