在tbl_summary表的某一行添加星号(*)(R)
我想根据缺失数据百分比是否超过10% 来在列名上添加星号。举例来说,在这个包含3 个变量的表中,我希望特征列显示为: "Age", "Result*" 和 "Group*"。
df <- data.frame(
Age = c(1:90, rep(NA, 10)), # 10% Missing
Result = c(1:80, rep(NA, 20)), # 20% Missing
Group = sample(c("A", "B", NA), 100, replace=TRUE) # Missingness varies
)
我正在使用R 语言中的一个很棒的gtsummary包,以及tbl_summary函数。到目前为止,我已经能够使用add_n计算缺失数据的百分比,但似乎无法让下一步生效。如有任何建议,敬请指教!
library(gtsummary)
table <- tbl_summary(df) |>
add_n("{p_miss}")
table |>
modify_table_styling(columns = label, rows = row_type == "label", label = ifelse(n > 10, paste0(label, "*"), label))
解决方案
Here's an example adding an asterix and also adding a note via a proper footnote as well.
library(gtsummary)
table <- trial |>
tbl_summary(
by = trt,
include = c(marker, age),
missing = "no"
) |>
add_n("{p_miss}", col_label = "**% Missing**")
# create a vector of variable names with missing rate >5% (there are plenty of ways to get this and this is just one example)
variables_big_missing <-
gather_ard(table)$add_n |>
cards::unlist_ard_columns() |>
dplyr::filter(stat_name == "p_miss", stat > 0.05) |>
dplyr::pull(variable)
table_final <- table |>
# add a star for variables with missing rate larger than %5
modify_table_body(
~ .x |>
dplyr::mutate(label = ifelse(variable %in% .env$variables_big_missing & row_type == "label", paste0(label, "*"), label))
) |>
# or you can do it via a proper footnote
modify_footnote_body(
footnote = "Missing rate > 5%",
columns = "label",
rows = variable %in% .env$variables_big_missing & row_type == "label"
)
创建于2026-06-07,使用 reprex v2.1.1
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。