gpt4 book ai didi

r - 在 R 中的数据框列表上取列平均值

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

这就是我想要做的。我的数据框有一个因子变量“国家”,我想根据国家/地区拆分数据框。然后,我想对每个国家的数据框的每个变量取列均值。

这里的数据:https://github.com/pourque/country-data

到目前为止我已经这样做了......

myList <- split(df1, df1$country)
for(i in 1:length(myList)) {
aggregate <- mapply(myList[[i]][,-c(38:39)], colMeans)
}

(我不包括第 38 和第 39 列,因为它们是因素。)

我读过这个( function over more than one list ),这让我觉得 mapply 是这里的答案......但我收到了这个错误:
Error in match.fun(FUN) : 
'myList[[i]][, -c(38:39)]' is not a function, character or symbol

也许我格式不正确?

最佳答案

使用 aggregate 在基础 R 中很简单无需split事先将 data.frame 放入一个列表中。这是一个使用内置虹膜数据的示例,您可以在其中计算 mean除第一列和第二列中的变量外的所有变量的分组Species :

data(iris)
aggregate(. ~ Species, iris[-(1:2)], mean)
# Species Petal.Length Petal.Width
#1 setosa 1.462 0.246
#2 versicolor 4.260 1.326
#3 virginica 5.552 2.026
.aggregate用于指定要使用除分组变量(在本例中为物种)之外的 data.frame 的所有剩余列。并且因为您指定了 iris[-(1:2)]作为输入数据,第一列和第二列也不使用。

对于您的数据,它应该是这样的:
aggregate(. ~ country, df1[-c(38:39)], mean)

关于r - 在 R 中的数据框列表上取列平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30035592/

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