R语言expss表格格式化:均值后置及新增条件汇总行实现方法
方案实现代码
以下代码可同时满足你两个需求,可直接运行测试:
library(expss) library(dplyr) # 预先设置变量标签和值标签 mtcars = modify(mtcars, { var_lab(cyl) = "Number of cylinders" var_lab(vs) = "Engine" val_lab(vs) = c("V-engine" = 0, "Straight engine" = 1) }) test_table <- mtcars %>% # 处理第一个变量cyl的所有统计 tab_cells(cyl) %>% tab_cols(total(label = "All")) %>% # 先算百分比和基础合计行 tab_stat_cpct( total_row_position = "below", total_statistic = c("u_cpct", "u_cases"), total_label = c("percent", "unweighted answers") ) %>% # 紧跟当前变量的均值 tab_stat_mean(label = "Mean") %>% # 插入自定义的cyl≥6占比行 tab_custom( fun = function(x) sum(x >= 6) / length(x) * 100, label = "Top2 (6 or more cyl)" ) %>% # 处理第二个变量vs的所有统计 tab_cells(vs) %>% tab_stat_cpct( total_row_position = "below", total_statistic = c("u_cpct", "u_cases"), total_label = c("percent", "unweighted answers") ) %>% tab_stat_mean(label = "Mean") %>% # 生成最终表格 tab_pivot(stat_label = "inside") # 查看结果 test_table
代码说明
- 均值位置调整:将原本统一放在所有统计后的
tab_stat_mean拆分到每个变量的独立统计流程中,每个变量跑完百分比和基础合计行后立即计算自身均值,自然就会跟在对应变量的合计项之后,不会集中堆在表格末尾。 - 自定义汇总行:使用
tab_custom函数可以在任意统计节点插入自定义计算的行,针对单个变量设置计算逻辑即可,生成的行会自动跟在当前变量的前一项统计(此处为均值)之后,位置完全符合需求。如果有多个变量需要加自定义汇总行,只需要在对应变量的统计流程中插入对应的tab_custom语句即可。
内容的提问来源于stack exchange,提问作者Loevet91
相关产品推荐
相关产品推荐

