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

如何调整gtsummary分层表格中cyl分组为6 Cylinder、4 Cylinder、8 Cylinder的顺序

调整gtsummary分层汇总的分组顺序

要实现按「6 Cylinder、4 Cylinder、8 Cylinder」的顺序展示分层汇总,核心是将cyl转换为因子型变量并自定义水平顺序(字符型变量默认按字典序排序,不符合需求)。修改后的完整代码如下:

library(tidyverse)
library(gtsummary)

tbl <- 
  mtcars %>%
  select(am, cyl, mpg, hp) %>%
  dplyr::mutate(
    # 将cyl转为字符后再转为因子,指定自定义水平顺序
    cyl = factor(paste(cyl, "Cylinder"), 
                 levels = c("6 Cylinder", "4 Cylinder", "8 Cylinder")),
    am = factor(am, labels = c("Automatic", "Manual"))
  ) %>%
  tbl_strata(
    strata = cyl,
    ~.x %>%
      tbl_summary(
        by = am,
        type = where(is.numeric) ~ "continuous"
      ) %>%
      modify_header(all_stat_cols() ~ "**{level}**")
  )

# 查看结果
tbl

关键修改说明

  • 原代码中cyl是字符型,默认按字典序排序("4 Cylinder"会排在最前)
  • 通过factor()函数指定levels参数,强制分层顺序为你需要的「6 Cylinder → 4 Cylinder → 8 Cylinder」
  • tbl_strata会严格遵循因子的水平顺序来生成分层表格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 10:45:15