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

如何在R的table1包中为不同变量指定数据框的不同子集?

解决table1中条件变量缺失值统计错误的问题

要统计type_resp_support时仅针对接受过呼吸支持的患者,排除未接受者的无效NA,可通过以下两种方法实现:

方法1:自定义统计函数

借助table1支持自定义统计逻辑的特性,为目标变量指定仅筛选received_resp_support == "yes"子集的函数:

library(table1)

# 示例数据
a <- data.frame(
  received_resp_support = c("no", "yes", "yes", "yes"),
  type_resp_support = factor(c(NA, "A", "B", NA))
)

# 自定义统计函数:仅统计接受呼吸支持的人群
resp_type_stats <- function(x, data) {
  sub_data <- data[data$received_resp_support == "yes", ]
  x_sub <- sub_data$type_resp_support
  cnts <- table(x_sub, useNA = "ifany")
  sapply(names(cnts), function(n) sprintf("%s (%0.1f%%)", cnts[n], 100*cnts[n]/length(x_sub)))
}

# 生成表格,指定自定义函数
table1(
  ~ received_resp_support + type_resp_support, 
  data = a,
  render.categorical = resp_type_stats,
  render.continuous = resp_type_stats
)

方法2:生成过滤后变量

先创建一个新变量,将未接受呼吸支持的患者标记为独立类别,再统计:

library(table1)

a <- data.frame(
  received_resp_support = c("no", "yes", "yes", "yes"),
  type_resp_support = factor(c(NA, "A", "B", NA))
)

# 生成过滤变量:未接受者标记为"未接受",其余保留原类型
a$resp_type_filtered <- ifelse(
  a$received_resp_support == "no", 
  "未接受呼吸支持", 
  as.character(a$type_resp_support)
)
a$resp_type_filtered <- factor(a$resp_type_filtered, levels = c("A", "B", NA, "未接受呼吸支持"))

# 生成表格
table1(~ received_resp_support + resp_type_filtered, data = a)

两种方法都能准确统计出接受呼吸支持人群中的真实缺失值(示例中为1个),避免混淆未接受支持的无效NA和真实缺失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 08:57:25