【问题标题】:Loop Aggregate with Weighted Mean in RR中加权平均值的循环聚合
【发布时间】:2021-08-31 18:59:28
【问题描述】:

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

我的数据当前有列(站、时间、层、深度、生物质_X、生物质_Y、生物质_Z,...),我想将其浓缩为(站、时间、加权深度_X、加权深度_Y、加权深度_Z,...)。

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

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

【问题讨论】:

    标签: r aggregation


    【解决方案1】:

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

    # 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)
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2021-02-01
      • 2019-04-29
      相关资源
      最近更新 更多