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

如何在R的gtsummary表格中按小数点对齐列数字?

解决gtsummary表格数字小数点对齐的问题

要实现列中数字按小数点对齐,你可以通过modify_table_styling结合gt的小数对齐功能完成,具体代码调整如下:

library(gtsummary)
library(gt)

theme_gtsummary_journal(journal = "jama")

gt::rx_adsl |>
  tbl_summary(
    include = c(SEX),
    by = TRTA,
    digits = all_categorical() ~ c(0, 1),
    missing = "no"
  ) |>
  # 针对所有统计列设置小数点对齐
  modify_table_styling(
    columns = all_stat_cols(),
    align = "decimal"
  )

关键说明:

  • all_stat_cols():自动选中tbl_summary生成的所有统计量列(即by分组对应的列),无需手动指定列名。
  • align = "decimal":调用gt的小数对齐规则,会自动识别数字中的小数点并完成对齐。

如果上述方法未生效(可能是主题样式覆盖了对齐设置),可以先将表格转换为gt对象,再直接用gt的样式函数强制设置:

gt::rx_adsl |>
  tbl_summary(
    include = c(SEX),
    by = TRTA,
    digits = all_categorical() ~ c(0, 1),
    missing = "no"
  ) |>
  as_gt() |>
  tab_style(
    style = cell_text(align = "decimal"),
    locations = cells_body(columns = everything()) # 对所有正文列应用对齐,可按需指定特定列
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 02:43:14