Use of other columns as arguments to function in summarize_if()

Viewed 70

This works great (see it as a solution for using list() instead of vars() here):

mtcars %>% 
  group_by(cyl) %>% 
  summarize_at(vars(disp, hp), list(~weighted.mean(., wt)))

However, in a very similar situation using summarize_if(), it does not work:

mtcars %>% 
  group_by(cyl) %>% 
  summarize_if(is.numeric, list(~weighted.mean(., wt)))

Error in weighted.mean.default(., wt) : 
  'x' and 'w' must have the same length

Why?

1 Answers

I believe this has to do with what you are naming this new variable. This works:

mtcars %>% 
     group_by(cyl) %>% 
     summarize_if(is.numeric, list(tmp = ~weighted.mean(., wt)))

See the naming section here and issues that have been noted here for more details.

Related