如何在gtsummary的tbl_summary中添加分段变量标题?
为gtsummary表格添加分段标题实现分组展示
问题描述
现有如下R代码创建gtsummary的tbl_summary表格:
table1 <- ptbl %>% dplyr::select( pt_gender.factor, pt_race.factor, pt_ethnicity.factor, education.factor, employed.factor,marital.factor, home_smoker.factor,quit_support.factor,past7.factor) %>% tbl_summary( label = list(pt_gender.factor ~ "Gender", pt_race.factor ~ "Race", pt_ethnicity.factor ~ "Ethnicity", education.factor ~ "Education", employed.factor ~ "Employed", marital.factor ~ "Marital Status", home_smoker.factor ~ "Live with smoker", quit_support.factor ~ "People around are very supportive of quitting smoking", past7.factor ~ "In the past 7 days, did you smoke a cigarette (even a puff)?"))
需要为表格添加两个分段标题:人口统计学特征(Demographics) 和 吸烟习惯(Smoking Habit),将现有变量分组对应展示。
解决方案
可以使用gtsummary包中的add_section()函数实现该需求,该函数支持为表格添加自定义分段标题,并指定对应变量组。修改后的代码如下:
table1 <- ptbl %>% dplyr::select( pt_gender.factor, pt_race.factor, pt_ethnicity.factor, education.factor, employed.factor,marital.factor, home_smoker.factor,quit_support.factor,past7.factor) %>% tbl_summary( label = list(pt_gender.factor ~ "Gender", pt_race.factor ~ "Race", pt_ethnicity.factor ~ "Ethnicity", education.factor ~ "Education", employed.factor ~ "Employed", marital.factor ~ "Marital Status", home_smoker.factor ~ "Live with smoker", quit_support.factor ~ "People around are very supportive of quitting smoking", past7.factor ~ "In the past 7 days, did you smoke a cigarette (even a puff)?")) %>% # 添加人口统计学特征分段 add_section( section = "**人口统计学特征(Demographics)**", rows = c("pt_gender.factor", "pt_race.factor", "pt_ethnicity.factor", "education.factor", "employed.factor", "marital.factor") ) %>% # 添加吸烟习惯分段 add_section( section = "**吸烟习惯(Smoking Habit)**", rows = c("home_smoker.factor", "quit_support.factor", "past7.factor") )
代码说明
add_section()的section参数用于设置分段标题文本,使用加粗突出显示标题rows参数指定该分段下包含的变量名(需与原始数据中的变量名一致)- 按需求将变量分为两组,分别对应两个分段标题,最终表格会按分组展示变量统计结果
内容的提问来源于stack exchange,提问作者mmmmmm
相关产品推荐
相关产品推荐

