R:残差建模
我听说人们在创建先验模型后想要计算一些效果时谈论“残差建模” 。例如,如果他们知道两个变量,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) ]
我的第一个建议方法存在收敛问题,但这就是我愚蠢的大脑会如何解决这个问题。谢谢你的帮助!