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

关于tbl_summary分位数计算算法类型及自定义的技术问询

关于tbl_summary分位数计算的问题解答

1. 默认采用的分位数算法类型

尽管tbl_summary参考文档提到{p##}语法对应quantile(probs=0.##, type=2),但实际测试结果表明:默认情况下tbl_summary使用的是stats::quantile的默认type=7算法。

用你提供的测试数据验证:

data <- data.table::data.table(values = c(120, 120, 140, 210))

tbl_summary(
    data,
    type = list(values ~ 'continuous'),
    statistic = list(values ~ "{p75}"),
    digits = everything() ~ 1
)

输出的75分位数为157.5,和stats::quantile(data$values, probs=0.75)(默认type=7)的结果完全一致,而非type=2算法得出的175。这说明文档中的示例描述存在偏差,实际默认行为是沿用stats::quantile的默认参数配置。

2. 修改分位数计算的type参数

可以通过自定义统计函数实现,绕过默认的{p##}语法,直接调用指定type的quantile函数:

基础实现示例

# 自定义分位数计算函数,指定type参数
custom_quantile <- function(x, probs, type = 2) {
  stats::quantile(x, probs = probs, type = type, na.rm = TRUE)
}

# 在tbl_summary中调用自定义函数
tbl_summary(
  data,
  type = list(values ~ "continuous"),
  statistic = list(
    values ~ c(
      "P25 = {custom_quantile(., probs=0.25, type=2)}",
      "P75 = {custom_quantile(., probs=0.75, type=2)}"
    )
  ),
  digits = everything() ~ 1
)

运行后会得到type=2算法下的分位数结果(P25=120,P75=175),满足小样本下IQR报告的需求。

封装简化(批量输出IQR)

如果需要直接输出IQR格式的结果,可以封装更简洁的函数:

# 封装返回type=2算法的IQR结果
iqr_type2 <- function(x) {
  q <- stats::quantile(x, probs = c(0.25, 0.75), type = 2, na.rm = TRUE)
  paste0(q[1], " (", q[2], ")")
}

# 直接调用封装函数
tbl_summary(
  data,
  type = list(values ~ "continuous"),
  statistic = list(values ~ "{iqr_type2(.)}"),
  digits = everything() ~ 1
)

输出结果会直接显示120 (175),符合医学/统计领域常见的IQR报告格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 11:27:40