简体   繁体   中英

Summarise for multiple group_by variables combined and individually

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.

For example if I run

mtcars %>% 
  group_by(cyl, vs) %>% 
  summarise(new = mean(wt))

I get

    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

But I want to get

    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

Ie get the mean for the variables both combined and individually

Edit Jaap 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...

Here is an idea using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM