如何使summary.matchit输出显示自定义变量标签?
解决方案
问题根源
你当前代码的核心问题有两个:一是**matchit调用时使用了原始的lalonde数据集,而非添加了自定义标签的mydf**,导致变量标签未被传入匹配模型;二是分类变量(如race)会被自动生成哑变量,需要手动将哑变量的行名替换为「自定义标签+哑变量后缀」的格式。
完整实现代码
library(MatchIt) library(labelled) library(magrittr) # 加载数据集并设置变量标签 mydf <- MatchIt::lalonde mydf %<>% set_variable_labels( age = "MyAge", educ = "MyEduc", race = "MyRace" ) # 调用matchit时使用带标签的mydf m.out0 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75, data = mydf, # 关键:改用处理后的mydf method = "quick", distance = "glm") # 提取匹配后的汇总结果 sum_mat <- summary(m.out0, un = FALSE)$sum.matched[seq(1,5), seq(1,2)] # 获取变量标签列表 var_labels <- var_label(mydf) # 替换行名为自定义标签(兼容分类哑变量) row_names <- rownames(sum_mat) for (i in seq_along(row_names)) { rn <- row_names[i] if (rn == "distance") next # 从哑变量名中提取原始变量(如从raceblack提取race) orig_var <- sub("(.*?)(black|hispan|white)?", "\\1", rn) lab <- var_labels[[orig_var]] # 拼接标签与哑变量后缀 if (grepl("(black|hispan|white)", rn)) { suffix <- sub(".*?(black|hispan|white)", "\\1", rn) new_rn <- paste0(lab, suffix) } else { new_rn <- lab } rownames(sum_mat)[i] <- new_rn } # 查看最终结果 sum_mat
输出结果
Means Treated Means Control distance 0.5774355466557 0.5764010328956 MyAge 25.8162162162162 25.4475708575709 MyEduc 10.3459459459459 10.6780791680792 MyRaceblack 0.8432432432432 0.8376126126126 MyRacehispan 0.0594594594595 0.0606976956977
内容的提问来源于stack exchange,提问作者robertspierre
相关产品推荐
相关产品推荐

