首页 文章

如何使用summarise_each计算加权平均值?

提问于
浏览
3

如何使用dplyr中的summarise_each计算数据集中所有字段的加权平均值?例如,假设我们要按 cylmtcars 数据集进行分组,并计算权重作为 gear 列的所有列的加权平均值 . 我尝试了以下但是无法让它工作 .

mtcars %>% group_by(cyl) %>% summarise_each(funs(weighted.mean(., gear)))

# The line above gives the following output
# Error in weighted.mean.default(c(1, 2, 2, 1, 2, 1, 1, 1, 2, 2, 2), 4.15555555555556) : 
# 'x' and 'w' must have the same length

在此先感谢您的帮助!

1 回答

  • 12

    为了帮助看看这里发生了什么 . 让我们创建一个返回其参数长度的函数

    lenxy <- function(x,y)
        paste0(length(x),'-',length(y))
    

    然后将其应用于 summarise_each ,如下所示:

    mtcars %>% group_by(cyl) %>% summarise_each(funs(lenxy(., qsec)))
    
    #>   cyl   mpg  disp    hp  drat    wt  qsec   vs   am gear carb
    #> 1   4 11-11 11-11 11-11 11-11 11-11 11-11 11-1 11-1 11-1 11-1
    #> 2   6   7-7   7-7   7-7   7-7   7-7   7-7  7-1  7-1  7-1  7-1
    #> 3   8 14-14 14-14 14-14 14-14 14-14 14-14 14-1 14-1 14-1 14-1
    

    查看此表,您可以看到第一个和第二个参数的长度在 qseq 之前是相同的,然后是 lenxy 的第二个参数的长度为1,这是dplyr对数据进行操作的结果放置,用它的摘要替换每个字段,而不是创建一个新的data.fame .

    解决方案很简单:从摘要中排除加权变量:

    mtcars %>% 
        group_by(cyl) %>% 
        summarise_each(funs(weighted.mean(., gear)),
                       -gear)
    

相关问题