Add margin row totals in dplyr chain

后端 未结 7 2167
一整个雨季
一整个雨季 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:18

    Here's a take on the accepted answer, using new functions introduced in dplyr 1.0.0 and tidyr 1.0.0.

    We pivot the counts using the new tidyr::pivot_wider. Then use the new dplyr::rowwise and dplyr::c_across to sum the counts for the total column.

    We can also use tidyr::pivot_longer to get in desired long format.

    library(dplyr, warn.conflicts = FALSE)
    library(tidyr)
    
    cyl_gear_sum <- mtcars %>%
      count(cyl, gear) %>%
      pivot_wider(names_from = gear, values_from = n, values_fill = list(n = 0)) %>%
      rowwise(cyl) %>%
      mutate(gear_total = sum(c_across()))
    
    cyl_gear_sum
    #> # A tibble: 3 x 5
    #> # Rowwise:  cyl
    #>     cyl   `3`   `4`   `5` gear_total
    #>            
    #> 1     4     1     8     2         11
    #> 2     6     2     4     1          7
    #> 3     8    12     0     2         14
    
    # total as row
    cyl_gear_sum %>% 
      pivot_longer(-cyl, names_to = "gear", values_to = "n")
    #> # A tibble: 12 x 3
    #>      cyl gear           n
    #>           
    #>  1     4 3              1
    #>  2     4 4              8
    #>  3     4 5              2
    #>  4     4 gear_total    11
    #>  5     6 3              2
    #>  6     6 4              4
    #>  7     6 5              1
    #>  8     6 gear_total     7
    #>  9     8 3             12
    #> 10     8 4              0
    #> 11     8 5              2
    #> 12     8 gear_total    14
    

    Created on 2020-04-07 by the reprex package (v0.3.0)

提交回复
热议问题