本文介绍了总结多个group_by变量组合和单独的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在使用dplyr的group_by,并且通过每个group_by变量组合来得出一个平均值,但也希望通过每个group_by变量单独获取平均值。I am using dplyr's group_by and summarise to get a mean by each group_by variable combined, but also want to get the mean by each group_by variable individually.例如如果我运行mtcars %>% group_by(cyl, vs) %>% summarise(new = mean(wt))我得到 cyl vs new <dbl> <dbl> <dbl> 4 0 2.140000 4 1 2.300300 6 0 2.755000 6 1 3.388750 8 0 3.999214但是我想要获得 cyl vs new <dbl> <dbl> <dbl> 4 0 2.140000 4 1 2.300300 4 NA 2.285727 6 0 2.755000 6 1 3.388750 6 NA 3.117143 8 0 3.999214 NA 0 3.688556 NA 1 2.611286获得组合和单独变量的平均值I.e. get the mean for the variables both combined and individually 编辑 Jaap将此标记为重复,并指向我使用聚合对几个变量应用几个函数一次通话。我看着那个引用dplyr的jaap的答案,但是我看不出我怎么回答我的问题?你说要使用 summarise_each ,但是我仍然看不到我可以如何使用它来单独通过变量获取每个组的平均值?抱歉,如果我是笨蛋...EditJaap marked this as duplicate and pointed me in the direction of Using aggregate to apply several functions on several variables in one call. I looked at jaap's answer there which referenced dplyr but I can't see how that answers my question? You say to use summarise_each, but I still don't see how I can use that to get the mean of each of my group by variables individually? Apologies if I am being stupid...推荐答案这是一个使用 bind_rows ,library(dplyr)mtcars %>% group_by(cyl, vs) %>% summarise(new = mean(wt)) %>% bind_rows(., mtcars %>% group_by(cyl) %>% summarise(new = mean(wt)) %>% mutate(vs = NA), mtcars %>% group_by(vs) %>% summarise(new = mean(wt)) %>% mutate(cyl = NA)) %>% arrange(cyl) %>% ungroup()# A tibble: 10 × 3# cyl vs new# <dbl> <dbl> <dbl>#1 4 0 2.140000#2 4 1 2.300300#3 4 NA 2.285727#4 6 0 2.755000#5 6 1 3.388750#6 6 NA 3.117143#7 8 0 3.999214#8 8 NA 3.999214#9 NA 0 3.688556#10 NA 1 2.611286 这篇关于总结多个group_by变量组合和单独的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-03 08:10