use of other columns as arguments to function in summarize_at()

瘦欲@ 提交于 2021-01-27 06:31:44

问题


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()?


回答1:


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  


来源:https://stackoverflow.com/questions/49395025/use-of-other-columns-as-arguments-to-function-in-summarize-at

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!