如何统一tbl_svysummary中add_differences()的舍入并移除CI列
调整gtsummary差异分析表格的格式
针对用gtsummary处理survey对象时遇到的格式问题,解决方案如下:
1. 移除CI列
在add_difference()中设置include_ci = FALSE,即可直接去掉置信区间列。
2. 统一差值与p值的小数位数
通过add_difference()的digits参数,指定差值(difference)和p值(p.value)的小数位数,与表格主体的3位小数保持一致。
修改后的完整代码
# Load necessary packages library(survey) library(dplyr) library(gtsummary) # Create a sample data frame with a weight variable set.seed(123) df <- data.frame( age_rs = runif(100, 18, 80), # rescaled age variable income_by_20_rs = runif(100, 0, 1), # rescaled income variable physical_health_poor = runif(100, 0, 1), # continuous physical health variable all_religion1 = runif(100, 0, 1), # continuous religious status variable racial_consciousness = runif(100, 0, 1), # rescaled racial consciousness number_discrim_areas_rs = runif(100, 0, 5), # number of discrimination areas (rescaled) vote_trump = factor(sample(c(0, 1), 100, replace = TRUE), labels = c("No", "Yes")), weights = runif(100, 0.5, 2) # weight variable ranging between 0.5 and 2 ) # Create survey design object with weights df_design <- svydesign(ids = ~1, data = df, weights = ~weights) # Make table using gtsummary tbl1 <- tbl_svysummary( data = df_design, by = "vote_trump", statistic = list(all_continuous() ~ "{mean} ({sd})"), include = c(age_rs, income_by_20_rs, physical_health_poor, all_religion1), label = list(age_rs = "Age", income_by_20_rs = "Income", physical_health_poor = "Poor Physical Health", all_religion1 = "Religious Devotion"), digits = list(all_continuous() ~ c(3,3)), missing = "no", type = list(c(age_rs, income_by_20_rs, physical_health_poor, all_religion1) ~ "continuous") ) %>% add_difference( include_ci = FALSE, # 移除CI列 digits = list( difference ~ 3, # 差值保留3位小数 p.value ~ 3 # p值保留3位小数 ) ) tbl1
关键参数说明
include_ci = FALSE:关闭置信区间列的输出,直接移除不需要的CI列。digits参数:针对差值和p值分别指定小数位数,与tbl_svysummary()中设置的3位小数完全匹配,保证表格格式统一。
内容的提问来源于stack exchange,提问作者Glebglob
相关产品推荐
相关产品推荐

