将 glm 与 data.table 以及预测变量和响应的参数定义一起使用

Use glm with data.table and a parametric definition of the predictors and the response

我想在数据集中进行 VIF 测试 运行连续回归,每次使用一个变量作为响应,其余变量作为预测变量。

为此,我会将我的代码放在一个 for 循环中,该循环将为将用作响应的列的索引提供连续的值,并将其余值留作预测变量。

我将使用 data.table 包,我将使用在基础 R 中找到的 mtcars 数据集来创建一个可重现的示例:

data(mtcars)
setDT(mtcars)
# Let i-- the index of the response -- be 1 for demonstration purposes
i <- 1
variables <- names(mtcars)
response <- names(mtcars)[i]
predictors <- setdiff(variables, response)
model <- glm(mtcars[, get(response)] ~ mtcars[, predictors , with = FALSE], family = "gaussian")

但是,这会导致错误消息:

Error in model.frame.default(formula = mtcars[, get(response)] ~ mtcars[, : invalid type (list) for variable 'mtcars[, predictors, with = FALSE]'

你能解释一下错误并帮助我更正代码吗?

我们将不胜感激您的建议。

============================================= ================================

编辑:

在重现建议的代码时我收到一条错误消息:

> library(car)
> library(data.table)
> 
> data(mtcars)
> setDT(mtcars)
> model <- glm(formula = mpg ~ .,data=mtcars ,  family = "gaussian")
> vif(model)
Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘vif’ for signature ‘"glm"’

更新:

当我明确指定包时,代码 运行 没有问题,即:

car::vif(model)

编辑 2

我不得不如下修改 Fredrik 的代码以获得所有变量的系数:

rhs <- paste(predictors,  collapse ="+")
full_formula <- paste(response, "~", rhs)
full_formula <- as.formula(full_formula)

如果您想计算预测变量的 VIF,我建议您查看包 car 中的 vif 函数。它将为您进行计算,并推广到具有多个自由度的预测变量,例如因子。

要获得所有的 vif,您只需要

library(car)
library(data.table)

data(mtcars)
setDT(mtcars)
model <- glm(formula = mpg ~ .,data=mtcars ,  family = "gaussian")
vif(model)

至于你的错误,我看到它是因为你混淆了 glm 它采用公式和数据集以及 glm.fit 它采用设计矩阵和预测,按顺序。您在调用中对这两个函数都有概念。

为了适合你的模型,我建议使用 glm,因为这会给你一个 class glm 的对象,具有额外的功能,例如能够执行 plot(model) 而不是glm.fit 其中您只获得与模型相关的值列表。

在那种情况下,您只需创建公式,看起来像:

library(data.table)

data(mtcars)
setDT(mtcars)
# Let i-- the index of the response -- be 1 for demonstration purposes
i <- 1
variables <- names(mtcars)
response <- names(mtcars)[i]
predictors <- setdiff(variables, response)


rhs <- paste(predictors, sep = " + ")
full_formula <- paste(response, "~", rhs)
model <- glm(formula = full_formula ,data=mtcars, family = "gaussian") 

对比于:

 model <- glm.fit(y=mtcars[, get(response)] ,
                  x=mtcars[, predictors , with = FALSE],
                  family=gaussian())

另一种解决方案是基于glm.fit的使用:

model <- glm.fit(x=mtcars[, ..predictors], y=mtcars[[response]], family = gaussian())