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

在R中生成SMD并绘图:无需完整预测模型,仅用处理概率

解决方案:仅用处理概率生成SMD并绘制Love图

步骤1:准备处理概率(PS)

假设你已经通过外部模型计算得到处理概率,存储在数据集的ps列中(比如lalonde$ps)。如果还未计算,可单独生成(示例如下,可替换为你的自定义模型):

# 单独计算处理概率(仅示例)
ps_model <- glm(treat ~ age + educ + race + married + nodegree + re74 + re75, 
                data = lalonde, family = binomial)
lalonde$ps <- predict(ps_model, type = "response")

步骤2:用处理概率生成权重

无需编写完整协变量公式,直接通过weightit的ps参数传入已有的处理概率生成IPW权重:

library(WeightIt)
library(cobalt)
data("lalonde", package = "cobalt")

# 仅传入处理概率生成权重
w.out <- weightit(treat ~ 1, data = lalonde, ps = lalonde$ps, method = "ps")

步骤3:绘制Love图(避免完整协变量公式)

两种方式任选,均无需写出完整预测模型公式:

方法1:先生成平衡统计对象再绘图

# 生成平衡统计量对象
bal_obj <- bal.tab(covs = c("age", "educ", "race", "married", "nodegree", "re74", "re75"),
                   treat = lalonde$treat, data = lalonde, weights = list(IPW = w.out))

# 绘制Love图
love.plot(bal_obj, 
          var.order = "alphabetical", binary = "std",
          abs = FALSE, colors = c("red", "blue"), 
          shapes = c("circle", "triangle"),
          sample.names = c("Unweighted", "PS Weighted"),
          line = FALSE,
          themes = list(theme(legend.position = "top")))

方法2:直接在love.plot中指定协变量

love.plot(treat ~ 1, data = lalonde, 
          covs = c("age", "educ", "race", "married", "nodegree", "re74", "re75"),
          weights = list(IPW = w.out),
          var.order = "alphabetical", binary = "std",
          abs = FALSE, colors = c("red", "blue"), 
          shapes = c("circle", "triangle"),
          sample.names = c("Unweighted", "PS Weighted"),
          line = FALSE,
          themes = list(theme(legend.position = "top")))

关键说明

  • 上述代码全程未出现完整预测模型公式,仅依赖预先生成的处理概率完成权重计算与绘图。
  • 若处理概率来自其他模型(如机器学习模型),只需将其传入weightit的ps参数即可,无需关联原始协变量公式。
  • covs参数通过列名向量指定需计算SMD的协变量,替代冗长的公式写法,更简洁灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:55:22