gpt4 book ai didi

r - 计算data.frame中多列的均值

转载 作者:行者123 更新时间:2023-12-04 09:59:27 27 4
gpt4 key购买 nike

只是想知道是否可以仅通过使用均值函数来计算多列的均值

例如

mean(iris[,1])

有可能,但没有
mean(iris[,1:4])

尝试过:
mean(iris[,c(1:4)])

收到此错误消息:

Warning message: In mean.default(iris[, 1:4]) : argument is not numeric or logical: returning NA



我知道我可以用
lapply(iris [,1:4],mean)
或者
sapply(iris [,1:4],平均)

最佳答案

试试colMeans:

但是该列必须为数字。您可以为更大的数据集为其添加测试。

colMeans(iris[sapply(iris, is.numeric)])
Sepal.Length Sepal.Width Petal.Length Petal.Width
5.843333 3.057333 3.758000 1.199333

基准

似乎很久 dplyrdata.table。也许有人可以复制调查结果的准确性。
microbenchmark(
plafort = colMeans(big.df[sapply(big.df, is.numeric)]),
Carlos = colMeans(Filter(is.numeric, big.df)),
Cdtable = big.dt[, lapply(.SD, mean)],
Cdplyr = big.df %>% summarise_each(funs(mean))
)
#Unit: milliseconds
# expr min lq mean median uq max
# plafort 9.862934 10.506778 12.07027 10.699616 11.16404 31.23927
# Carlos 9.215143 9.557987 11.30063 9.843197 10.21821 65.21379
# Cdtable 57.157250 64.866996 78.72452 67.633433 87.52451 264.60453
# Cdplyr 62.933293 67.853312 81.77382 71.296555 91.44994 182.36578

数据
m <- matrix(1:1e6, 1000)
m2 <- matrix(rep('a', 1000), ncol=1)
big.df <- as.data.frame(cbind(m2, m), stringsAsFactors=F)
big.df[,-1] <- lapply(big.df[,-1], as.numeric)
big.dt <- as.data.table(big.df)

关于r - 计算data.frame中多列的均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30941504/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com