You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在expss中生成含两类总计行的列百分比交叉表?

解决方案:expss生成带双总计行的列百分比交叉表

问题需求

需要用expss生成列百分比交叉表,要求:

  • 每个行变量组(如Number of cylinders、Engine)上方添加加权有效N(w_responses)总计行(标注为Total N)
  • 每个行变量组下方添加加权有效百分比(w_cpct)总计行(标注为Total %)

之前尝试两次全局调用tab_stat_cpct导致行重复,拆分设置统计量的方式又无法让所有行组同时拥有两类总计行。

可行代码

library(expss)

mtcars = apply_labels(mtcars,
                      cyl = "Number of cylinders",
                      am = "Transmission",
                      am = c("Automatic" = 0,
                             "Manual"=1),
                      vs = "Engine",
                      vs = c("V-Shaped" = 0,
                             "Straight"=1)
)

mtcars %>% 
    tab_cols(total(), am) %>% 
    # 为第一个行变量组配置两类总计
    tab_cells(cyl) %>% 
    tab_stat_cpct(total_row_position = "above",
                  total_statistic = "w_responses",
                  total_label = "Total N") %>% 
    tab_stat_cpct(total_row_position = "below",
                  total_statistic = "w_cpct",
                  total_label = "Total %") %>% 
    # 为第二个行变量组配置两类总计
    tab_cells(vs) %>% 
    tab_stat_cpct(total_row_position = "above",
                  total_statistic = "w_responses",
                  total_label = "Total N") %>% 
    tab_stat_cpct(total_row_position = "below",
                  total_statistic = "w_cpct",
                  total_label = "Total %") %>% 
    tab_pivot()

输出结果

|                     |          | #Total | Transmission |        |
 |                     |          |        |    Automatic | Manual |
 | ------------------- | -------- | ------ | ------------ | ------ |
 | Number of cylinders | #Total N |   32.0 |         19.0 |   13.0 |
 |                     |        4 |   34.4 |         15.8 |   61.5 |
 |                     |        6 |   21.9 |         21.1 |   23.1 |
 |                     |        8 |   43.8 |         63.2 |   15.4 |
 |                     | #Total % |  100.0 |        100.0 |  100.0 |
 |              Engine | #Total N |   32.0 |         19.0 |   13.0 |
 |                     | V-Shaped |   56.2 |         63.2 |   46.2 |
 |                     | Straight |   43.8 |         36.8 |   53.8 |
 |                     | #Total % |  100.0 |        100.0 |  100.0 |

关键说明

  • 核心思路是针对每个行变量组单独配置统计量:对cyl和vs分别调用tab_cells,并为每个变量同时添加上方的w_responses总计和下方的w_cpct总计。
  • 避免全局调用两次tab_stat_cpct,否则会导致所有行变量的统计结果重复输出。

内容的提问来源于stack exchange,提问作者Megan Brown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 02:25:35