R中具有加权平均值的循环聚合

时间:2021-06-15 20:02:14

标签: r aggregation

提前为措辞道歉,英语不是我的母语,这是我的第一篇文章。到目前为止,我已经能够汇总我的数据,但是在进一步压缩数据时遇到了问题。我正在尝试通过几种物种的生物量获得加权平均深度。

我的数据当前有列(站、时间、层、深度、生物量_X、生物量_Y、生物量_Z、...),我想将其压缩为(站、时间、weighted_depth_X、weighted_depth_Y、weighted_depth_Z、...)。

我让这段代码起作用了,但是有没有办法循环它以便它可以完成我的所有列?

    library(plyr)
    newData<-ddply(data, ~station+time, summarize, weighted.mean(data[,6], w=depth))

Data Table, formatting not look right when post

1 个答案:

答案 0 :(得分:0)

当然有更好的方法,但这应该有效:

# data: dataframe containing columns to be averaged
# weights: vector containing the corresponding weights
weighted_mean_all_cols<- function(data,weights){
  res<-do.call(cbind,llply(colnames(data), function(col) {weighted.mean(data[,col], w=weights)}))
  colnames(res) <- colnames(data)
  res
}

# collect the names of the target columns to average
targetCols <-  grep("^biomass",colnames(data))
# apply weighted average by group, for every target column
newData <- ddply(data, c('station','time'), function(groupDF) { 
  print(groupDF[targetCols])
  weighted_mean_all_cols(groupDF[,targetCols],groupDF$depth)
})