如何在R语言expss包生成的统计表格中新增分组差值列
expss交叉表新增分组差值列实现方案
直接对生成的透视表对象做列运算即可新增差值列,逻辑简单且不会破坏原有表格标签结构,完整实现代码如下:
library(expss) data(mtcars) mtcars = apply_labels(mtcars, mpg = "Miles/(US) gallon", cyl = "Number of cylinders", disp = "Displacement (cu.in.)", hp = "Gross horsepower", drat = "Rear axle ratio", wt = "Weight (1000 lbs)", qsec = "1/4 mile time", vs = "Engine", vs = c("V-engine" = 0, "Straight engine" = 1), am = "Transmission", am = c("Automatic" = 0, "Manual"=1), gear = "Number of forward gears", carb = "Number of carburetors" ) # 先生成基础交叉表并赋值给对象 res_table = mtcars %>% tab_cells(cyl, disp) %>% tab_cols(vs) %>% tab_stat_mean() %>% tab_pivot() # 按规则新增差值列:V-engine统计值减去Straight engine统计值 res_table[["差值(V-engine - Straight engine)"]] = res_table[["V-engine"]] - res_table[["Straight engine"]] # 输出最终表格 res_table
运行后生成的表格如下:
| | | Engine | | | | | | V-engine | Straight engine | 差值(V-engine - Straight engine) | | --------------------- | ---- | -------- | --------------- | ------------------------------------ | | Number of cylinders | Mean | 7.4 | 4.6 | 2.8 | | Displacement (cu.in.) | Mean | 307.1 | 132.5 | 174.6 |
补充说明
- 这个方法对所有
tab_stat_*生成的数值统计量都适用,不管是均值、中位数、标准差还是比例,都可以直接用对应列做运算。 - 如果需要调整列的顺序,可以在生成差值列后,通过列索引重排数据框顺序即可,比如要把差值列放到两个分组列中间,直接调整列位置就行。
- 如果需要给差值列添加变量标签,直接用
var_lab(res_table[["差值(V-engine - Straight engine)"]]) = "均值差"即可,和expss原有标签逻辑完全兼容。
内容的提问来源于stack exchange,提问作者Dat Vuong
相关产品推荐
相关产品推荐

