我想在数据集中运行连续回归的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")
但是,这会导致错误消息:
model.frame.default中的错误(公式= mtcars [,get(响应)] ~mtcars [,:变量'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)
2 回答
另一个解决方案是基于
glm.fit
的使用:如果你想计算预测变量的VIF,我建议你查看包
car
中的vif
函数 . 它将为您进行计算并推广具有多个自由度的预测变量,例如因子 .要获得你想要的所有vif
至于你的错误,我看到它正在混合
glm
,它采用公式和数据集,glm.fit
采用设计矩阵和预测,按此顺序 . 您的通话中有两个功能的概念 .为了适合你的模型,我建议使用
glm
,因为这将为你提供一个类glm的对象,具有额外的功能,例如能够做plot(model)
而不是glm.fit
,你只能获得与模型相关的值列表 .在这种情况下,你只需要创建公式,看起来像:
与之相反: