如何为R的DataFrame按school_type与staff_type子组添加总计行?
按双分组添加总计行的R语言实现
原始数据
data <- data.frame(school_type = c("nursery", "nursery", "nursery", "nursery", "primary", "primary", "primary", "primary"), staff_type = c("manager", "manager", "teacher", "teacher", "manager", "manager", "teacher", "teacher"), age_group = c("20-30","30-40","20-30","30-40","20-30","30-40","20-30","30-40"), number_staff = c(40, 10, 20, 30, 40, 10, 20, 30), perc_staff = c(80, 20,40,60,80, 20,40,60))
需求说明
为每个school_type和staff_type的组合子组添加总计行,汇总number_staff和perc_staff字段。
修改后的解决方案
方案1:基于split函数的实现
将原代码的单字段拆分改为按两个字段的组合拆分,即可实现双分组添加总计:
library(dplyr) library(purrr) library(janitor) data %>% arrange(school_type, staff_type) %>% split(list(.$school_type, .$staff_type)) %>% map_df(adorn_totals, where = "row")
方案2:基于group_split的tidyverse风格实现
更符合tidyverse语法习惯的写法,用group_by定义分组后拆分:
library(dplyr) library(purrr) library(janitor) data %>% arrange(school_type, staff_type) %>% group_by(school_type, staff_type) %>% group_split() %>% map_df(~ adorn_totals(.x, where = "row"))
代码说明
arrange(school_type, staff_type):按两个分组字段排序,确保子组内数据顺序统一split(list(.$school_type, .$staff_type))/group_by(...) %>% group_split():将数据按school_type和staff_type的组合拆分为多个子数据框map_df(adorn_totals, where = "row"):对每个子数据框添加行总计,自动汇总数值型字段(如number_staff求和,perc_staff求和),最后合并为一个完整的数据框
内容的提问来源于stack exchange,提问作者fe108
相关产品推荐
相关产品推荐

