问题描述
所以我正在编写一个循环来递归地从大型回归中删除最不重要的系数。
一切看起来都很好,直到 as.formula() 行,它给出了特定回归量不存在的错误代码。我检查了数据框,它在那里,一切看起来都很好。 paste() 很好。我不明白出了什么问题。
reg <- lm(price ~ .^2,data.cards)
coeff <- as.data.frame(summary(reg)$coefficients[,4,drop = FALSE])
while(coeff[which.max(coeff[,1]),]>0.01){
least.significant <- rownames(coeff[which.max(coeff[,drop = FALSE])
reg.equation <-as.formula(paste(least.significant,collapse = "-" ))
reg <- update(reg,reg.equation)
coeff <- data.frame(summary(reg)$coefficients[,drop = FALSE])
}
解决方法
请提供数据和您的问题。如果没有可重现的示例,有时很难猜测发生了什么,但我认为以下内容说明了这个问题。
reg <- lm(mpg ~ .^2,mtcars[,1:4])
coeff <- as.data.frame(summary(reg)$coefficients[,4,drop = FALSE])
while(coeff[which.max(coeff[,1]),]>0.01){
least.significant <- rownames(coeff[which.max(coeff[,drop = FALSE])
reg.equation <-as.formula(paste(least.significant,collapse = "-" ))
reg <- update(reg,reg.equation)
coeff <- data.frame(summary(reg)$coefficients[,drop = FALSE])
}
类中的错误(ff)
注意第一步中的least.significant
是"disp:hp"
,这不能被强制转换为公式:
as.formula("disp:hp")
as.formula("disp:hp + hp")
等,但 as.formula("~ disp:hp")
会起作用。对此有一个有用的函数 reformulate
,它采用术语和响应的字符向量,因此在下面的示例中,您只需要更改 reg.equation <-
行即可:
reg <- lm(mpg ~ .^2,drop = FALSE])
reg.equation <- reformulate(setdiff(names(coef(reg)[-1]),least.significant),'.')
reg <- update(reg,drop = FALSE])
}
coef(reg)
# (Intercept) cyl disp cyl:disp
# 49.03721186 -3.40524372 -0.14552575 0.01585388