汇总表格并添加占比

news
Author

Tony Duan

Published

October 10, 2022

Code
library(tidyverse)

汇总表格

Code
head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

按照1个变量汇总。并添加占比

Code
mtcars %>% group_by(cyl) %>% summarise(row_record=n(),total_hp=sum(hp)) %>% 
  mutate(total_hp_share = round(total_hp / sum(total_hp),2))
# A tibble: 3 × 4
    cyl row_record total_hp total_hp_share
  <dbl>      <int>    <dbl>          <dbl>
1     4         11      909           0.19
2     6          7      856           0.18
3     8         14     2929           0.62

按照2个变量汇总。并添加子分组占比

Code
mtcars %>% group_by(cyl,vs) %>% summarise(row_record=n(),total_hp=sum(hp)) %>% 
  mutate(total_hp_share = round(total_hp / sum(total_hp),2))
# A tibble: 5 × 5
# Groups:   cyl [3]
    cyl    vs row_record total_hp total_hp_share
  <dbl> <dbl>      <int>    <dbl>          <dbl>
1     4     0          1       91           0.1 
2     4     1         10      818           0.9 
3     6     0          3      395           0.46
4     6     1          4      461           0.54
5     8     0         14     2929           1   

按照2个变量汇总。并添加总占比

Code
mtcars %>% group_by(cyl,vs) %>% summarise(row_record=n(),total_hp=sum(hp)) %>% 
  ungroup() %>%
  mutate(total_hp_share = round(total_hp / sum(total_hp),2))
# A tibble: 5 × 5
    cyl    vs row_record total_hp total_hp_share
  <dbl> <dbl>      <int>    <dbl>          <dbl>
1     4     0          1       91           0.02
2     4     1         10      818           0.17
3     6     0          3      395           0.08
4     6     1          4      461           0.1 
5     8     0         14     2929           0.62

Reference