Add margin row totals in dplyr chain

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

    One option is with do

    mtcars %>%
       count(cyl, gear) %>%
       ungroup() %>% 
       mutate(cyl=as.character(cyl)) %>% 
       do(bind_rows(., data.frame(cyl="Total", count(mtcars, gear)))) 
       #or replace the last 'do' step with 
       #bind_rows(cbind(cyl='Total', count(mtcars, gear))) #from  @JonnyPolonsky's comments
    
    #      cyl  gear     n
    #     
    #1      4     3     1
    #2      4     4     8
    #3      4     5     2
    #4      6     3     2
    #5      6     4     4
    #6      6     5     1
    #7      8     3    12
    #8      8     5     2
    #9  Total     3    15
    #10 Total     4    12
    #11 Total     5     5
    

提交回复
热议问题