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

如何将tbl_summary中分类变量的{p}%显示改为比例值?

解决tbl_summary分类变量显示比例值(而非百分比)的问题

要把分类变量的显示从百分比(如48%)改成原始比例值(如0.48),不需要换用datasummary,直接在原tbl_summary代码基础上做两处修改即可:

关键修改点

  • 把统计量占位符从{p}%改为{p}:{p}本身就是0-1区间的原始比例值,加%是自动转为百分比的格式
  • 用modify_fmt_fun()指定分类变量的数值格式,避免默认显示过多小数位

修改后的完整代码

tbl_summary(data = CPS, by = "Type",
            include = c(Female, Hispanic,
                        age,
                        DadGradCollege,
                        MomGradCollege,
                        ftotval_def
                        ),
            statistic = list(all_continuous() ~ "{mean} \n({sd})",
                             all_categorical() ~ "{p}"),  # 去掉%,保留原始比例
            label = list(
              Female~ "Female",
              Hispanic ~ "Hispanic",
              age ~ "Age",
              DadGradCollege ~ "Fathers with \n \t College", 
              MomGradCollege ~ "Mothers with \n \t College",
              ftotval_def ~ "Total Family Income \n \t (1999 dollars)"
              ),
            missing = "no") %>%
  modify_fmt_fun(all_categorical() ~ style_number(digits = 2))  # 设置比例显示的小数位数

补充说明

  • 如需调整小数位数,修改style_number(digits = X)中的X值即可
  • 连续变量的{mean} \n({sd})格式不受影响,依然会在平均值下方括号里显示标准差
  • 之前用style_percent无效是因为它的作用是把比例转为百分比格式,和需求相反,所以要用style_number格式化原始比例值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:55:34