【问题标题】:Aggregate an entire data frame with Weighted Mean使用加权平均值聚合整个数据框
【发布时间】:2014-08-09 02:32:48
【问题描述】:

我正在尝试使用函数weighted.mean 聚合数据框并继续出现错误。我的数据如下所示:

dat <- data.frame(date, nWords, v1, v2, v3, v4 ...)

我尝试了类似的方法:

aggregate(dat, by = list(dat$date), weighted.mean, w = dat$nWords)

但是得到了

 Error in weighted.mean.default(X[[1L]], ...) : 
  'x' and 'w' must have the same length

还有另一个线程使用 plyr 回答了这个问题,但只有一个变量,我想以这种方式聚合我的所有变量。

【问题讨论】:

  • 是您在代码中拼错了weighted.mean 的问题吗?
  • 我相信weighted.mean 期望w 是由aggregate 切片的块的长度,它对应于每个因子级别(或组合)的元素数。因此,您只能使用一个权重,假设每个因子水平的元素数量相等。您可能应该编写一个自定义函数并使用mapplyaggregateing 准备w

标签: r aggregate weighted-average


【解决方案1】:

你可以用 data.table 做到这一点:

 library(data.table)

 #set up your data

 dat <- data.frame(date = c("2012-01-01","2012-01-01","2012-01-01","2013-01-01",
 "2013-01-01","2013-01-01","2014-01-01","2014-01-01","2014-01-01"), 
 nwords = 1:9, v1 = rnorm(9), v2 = rnorm(9), v3 = rnorm(9))

 #make it into a data.table

 dat = data.table(dat, key = "date")

 # grab the column names we want, generalized for V1:Vwhatever

 c = colnames(dat)[-c(1,2)]

 #get the weighted mean by date for each column

 for(n in c){
 dat[,
     n := weighted.mean(get(n), nwords),
     with = FALSE,
     by = date]
 }

 #keep only the unique dates and weighted means

 wms = unique(dat[,nwords:=NULL])

【讨论】:

    【解决方案2】:

    尝试使用by

    # your numeric data
    x <- 111:120
    
    # the weights
    ww <- 10:1 
    
    mat <- cbind(x, ww)
    
    # the group variable (in your case is 'date')
    y <- c(rep("A", 7), rep("B", 3))
    
    by(data=mat, y, weighted.mean)
    

    如果您想要数据框中的结果,我建议使用plyr 包:

    plyr::ddply(data.frame(mat), "y", weighted.mean)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      • 1970-01-01
      • 2021-08-31
      • 2014-11-30
      相关资源
      最近更新 更多