我听说人们在建立先验模型后想要计算一些效果时谈论“残差建模”。例如,如果他们知道两个变量,var_1
和 var_2
是相关的,我们首先用 var_1
做一个模型然后模拟 var_2
的效果然后。我的问题是我在实践中从未见过这样做过。
我对以下内容感兴趣:
glm
,我怎么占link function
用过的? glm
与 var_2
作为解释变量?我认为这与 1 相关。
我的尝试 :
dt <- data.table(mtcars) # I have a hypothesis that `mpg` is a function of both `cyl` and `wt`
dt[, cyl := as.factor(cyl)]
model <- stats::glm(mpg ~ cyl, family=Gamma(link="log"), data=dt) # I want to model `cyl` first
dt[, pred := stats::predict(model, type="response", newdata=dt)]
dt[, res := mpg - pred]
# will this approach work?
model2_1 <- stats::glm(mpg ~ wt + offset(pred), family=Gamma(link="log"), data=dt)
dt[, pred21 := stats::predict(model2_1, type="response", newdata=dt) ]
# or will this approach work?
model2_2 <- stats::glm(res ~ wt, family=gaussian(), data=dt)
dt[, pred22 := stats::predict(model2_2, type="response", newdata=dt) ]
我的第一个建议方法存在收敛问题,但这就是我愚蠢的大脑处理这个问题的方式。谢谢你的帮助!
最佳答案
从某种意义上说,ANCOVA 是“对残差建模”。 ANCOVA 的模型是 y_i = grand_mean +treatment_i + b * (covariate - covariate_mean_i) + 每个处理 i 的误差。术语 (covariate - covariate_mean_i) 可以看作是一个模型的残差,协变量为 DV,处理为 IV。
下面的回归等价于这个 ANCOVA:
lm(y ~ treatment * scale(covariate, scale = FALSE))
应用于数据的内容如下所示:lm(mpg ~ factor(cyl) * scale(wt, scale = FALSE), data = mtcars)
并且可以变成glm
类似于您在示例中使用的那个:glm(mpg ~ factor(cyl) * scale(wt, scale = FALSE),
family=Gamma(link="log"),
data = mtcars)
关于R:残差建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67385128/