Add margin row totals in dplyr chain

后端 未结 7 2165
一整个雨季
一整个雨季 2020-12-05 00:25

I would like to add overall summary rows while also calculating summaries by group using dplyr. I have found various questions asking how to do this, e.g. here, here, and he

7条回答
  •  萌比男神i
    2020-12-05 01:19

    An addition to @arkrun's answer that is not easy to add as a comment:

    Although a little more complex, this format allows for previous modifications in the data frame. Useful when there is a longer chain of verbs before the table is generated. (You want to change names, or select only specific variables)

    mtcars %>%
       count(cyl, gear) %>%
       ungroup() %>% 
       mutate(cyl=as.character(cyl))
    bind_rows(group_by(.,gear) %>%
                  summarise(n=sum(n)) %>%
                  mutate(cyl='Total')) %>%
    spread(cyl)
    
    ## A tibble: 3 x 5
    #   gear   `4`   `6`   `8` Total
    #*     
    #1     3     1     2    12    15
    #2     4     8     4     0    12
    #3     5     2     1     2     5
    

    This can also be doubled up to generate a total row for the spread as well.

    mtcars %>%
      count(cyl, gear) %>%
      ungroup() %>% 
      mutate(cyl=as.character(cyl),
             gear = as.character(gear)) %>%
      bind_rows(group_by(.,gear) %>%
                  summarise(n=sum(n)) %>%
                  mutate(cyl='Total')) %>%
      bind_rows(group_by(.,cyl) %>%
                  summarise(n=sum(n)) %>%
                  mutate(gear='Total')) %>%
      spread(cyl,n,fill=0)
    
    # A tibble: 4 x 5
       gear   `4`   `6`   `8` Total
    *     
    1     3     1     2    12    15
    2     4     8     4     0    12
    3     5     2     1     2     5
    4 Total    11     7    14    32
    

提交回复
热议问题