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

如何将gtsummary生成的调查汇总表因子水平从行转列?

用gtsummary实现多等级问卷的列向展示

要将问卷答案的各等级设为列展示,核心是先把宽格式的问卷数据转成长格式,再借助tbl_summary的by参数按答案等级分组,即可得到行是问题、列是等级的表格。

修改后的完整代码

library(gtsummary)
library(tidyr)
library(dplyr)

# 1. 将宽格式问卷数据转成长格式
physician_long <- physician[, 32:43] %>%
  pivot_longer(
    cols = everything(),
    names_to = "Item",  # 原列名作为问题项
    values_to = "Response"  # 答案等级作为响应值
  )

# 2. 生成列向展示的汇总表
table4 <- physician_long %>%
  tbl_summary(
    by = Response,  # 按答案等级拆分列
    label = list(Item ~ "Item"),
    statistic = list(all_categorical() ~ "{n} ({p}%)")  # 显示频数+百分比
  ) %>%
  modify_footnote(all_stat_cols() ~ "Frequency (%)") %>%
  modify_caption("**Table 7. The frequency with which prescribers provided antibiotics or resources related to prudent use of antibiotics, behavior on drivers for initiating prescriptions and antibiotic prescribing behaviors**") %>%
  modify_header(label ~ "Item") %>%
  bold_labels()

关键说明

  • pivot_longer:将原数据中每个问卷问题(32-43列)转换为单独一行,同时提取出对应的答案等级,这是实现列向展示的基础。
  • by = Response:指定按答案等级拆分列,每个等级自动成为表格的一列。
  • 若需要自定义列的顺序(比如按SA、A、D、SD的逻辑排序),可添加以下代码:
table4 <- table4 %>%
  modify_column_order(c(label, "SA", "A", "D", "SD", "N/A", "U", "IDU"))

内容的提问来源于stack exchange,提问作者gehan harb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 15:46:03