【发布时间】:2016-05-02 06:53:52
【问题描述】:
我有包含不同季节气候数据的示例数据集:
df <- data.frame(season=rep(1:5,2),year=rep(1:2,each=5),
temp=c(2,4,3,5,2,4,1,5,4,3),ppt=c(4,3,1,5,6,2,1,2,2,2),
samples=c(22,25,24,31,31,29,28,31,30,32))
我可以简单地确定每年每个季节的气候变量的平均值:
aggregate(df[,c('temp','ppt')], by = list(df$season,df$year), function(x) mean(x,na.rm=T))
但是,我想使用变量samples 作为我的权重来确定每个季节|年份组合的加权平均值。
基本上我想用weighted.mean 替换aggregate() 中的mean 函数。这需要向我的函数添加第二个参数,该参数需要用我的x 进行更改。
function(x,w) weighted.mean(x,w,na.rm=T))
不过,我不确定如何让weighted.mean() 的权重参数 ('w') 随聚合数据的每个子集而变化。
我可以在 aggregate 函数中完成这一切吗?
任何建议都会很棒!
【问题讨论】:
标签: r function arguments aggregate