[英]How to calculate the mean in a data frame using aggregate function in R?
我有一個數據框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
我想得到每年的項目數的平均值,所以我嘗試使用這個功能:
mean.df1=aggregate((df1$number*df1$Prop),list(df1$year), mean)
但它返回錯誤的平均值。 我希望它返回:
Group.1 x
1 2000 2.918918
2 2015 2.296296
其中Group.1是年份,x是正確的平均值。
謝謝!
aggregate
平均項目數/年
aggregate(number ~ year, data=df1, mean)
# year number
# 1 2000 3.000000
# 2 2015 2.666667
對於基數R的加權平均值,您可以進行標准的分割 - 應用 - 組合
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
如何使用dplyr
包
library(dplyr)
df1 %>% group_by(year) %>% summarise(mean = sum(number * items)/sum(items))
這使
year mean
1 2000 2.918919
2 2015 2.818182
我只需要在我的聚合函數中將“mean”切換為“sum”,使其變為:
mean.df1=aggregate((df1$number*df1$Prop),list(df1$year), sum)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.