dplyr中多列的加权平均值

Jan*_*Jan 9 r mean weighted dplyr

我正在尝试使用dplyr计算多列的加权平均值.目前我仍然坚持使用summarize_each,这对我来说似乎是解决方案的一部分.这是一些示例代码:

library(dplyr)
f2a <- c(1,0,0,1)
f2b <- c(0,0,0,1)
f2c <- c(1,1,1,1)
clustervar <- c("A","B","B","A")
weight <- c(10,20,30,40)

df <- data.frame (f2a, f2b, f2c, clustervar, weight, stringsAsFactors=FALSE)
df
Run Code Online (Sandbox Code Playgroud)

我正在寻找的是类似的东西

df %>%
  group_by (clustervar) %>%
  summarise_each(funs(weighted.mean(weight)), select=cbind(clustervar, f2a:f2c))
Run Code Online (Sandbox Code Playgroud)

结果只是:

# A tibble: 2 × 4
  clustervar select4 select5 select6
       <chr>   <dbl>   <dbl>   <dbl>
1          A      25      25      25
2          B      25      25      25
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?

ali*_*ire 15

您可以使用它summarise_at来指定要操作的列:

df %>% group_by(clustervar) %>% 
    summarise_at(vars(starts_with('f2')), 
                 funs(weighted.mean(., weight)))
#> # A tibble: 2 × 4
#>   clustervar   f2a   f2b   f2c
#>        <chr> <dbl> <dbl> <dbl>
#> 1          A     1   0.8     1
#> 2          B     0   0.0     1
Run Code Online (Sandbox Code Playgroud)