Reputation: 473
This works great:
> mtcars %>% group_by(cyl) %>% summarize_at(vars(disp, hp), weighted.mean)
# A tibble: 3 x 3
cyl disp hp
<dbl> <dbl> <dbl>
1 4.00 105 82.6
2 6.00 183 122
3 8.00 353 209
But now I want to use one of the columns from mtcars as the w argument to weighted.mean. Sadly, the obvious attempt fails:
> mtcars %>% group_by(cyl) %>% summarize_at(vars(disp, hp), weighted.mean, w = wt)
Error in dots_list(...) : object 'wt' not found
Even though wt is, indeed, part of mtcars. How can I use other columns as arguments to a function within summarize_at()?
Upvotes: 4
Views: 206
Reputation: 24198
You could try the funs()
syntax:
mtcars %>% group_by(cyl) %>%
summarize_at(vars(disp, hp), funs(weighted.mean(.,wt)))
# cyl disp hp
# <dbl> <dbl> <dbl>
#1 4.00 110 83.4
#2 6.00 185 122
#3 8.00 362 209
Upvotes: 3