如何使用R中的聚合函数计算数据框中的均值? [英] How to calculate the mean in a data frame using aggregate function in R?
本文介绍了如何使用R中的聚合函数计算数据框中的均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据帧df1:
I have a data frame df1:
number=c(4,3,2,3,4,1)
year=c("2000","2000","2000", "2015", "2015", "2015")
items=c(12, 10, 15, 5, 10, 7)
df1=data.frame(number, year, items)
setDT(df1)[, Prop := number/sum(number), by = year]
看起来像这样:
number year items Prop
1: 4 2000 12 0.4444444
2: 3 2000 10 0.3333333
3: 2 2000 15 0.2222222
4: 3 2015 5 0.3750000
5: 4 2015 10 0.5000000
6: 1 2015 7 0.1250000
我想获得每年项数的平均值,因此我尝试使用此功能:
I want to get the mean of the number of items per year, so I tried using this fuction:
mean.df1=aggregate((df1$number*df1$Prop),list(df1$year), mean)
但返回错误值卑鄙的我希望它返回:
but it returns the wrong values for the mean. I want it to return:
Group.1 x
1 2000 2.918918
2 2015 2.296296
其中Group.1是年份,x是正确的平均值。
where Group.1 is the year and x is the correct mean.
谢谢!
推荐答案
求平均值
项/年
aggregate(number ~ year, data=df1, mean)
# year number
# 1 2000 3.000000
# 2 2015 2.666667
编辑
对于基数R中的加权平均值,您可以执行标准的split-apply-combine
Edit
For the weighted average in base R you could do standard split-apply-combine
sapply(split(df1, df1$year), function(x) weighted.mean(x$number, w=x$items))
或
sapply(split(df1, df1$year), function(x) sum(x$number*x$items)/sum(x$items))
# 2000 2015
# 2.918919 2.818182
这篇关于如何使用R中的聚合函数计算数据框中的均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文