微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

As.formula 在循环中不起作用? 调整回归

如何解决As.formula 在循环中不起作用? 调整回归

所以我正在编写一个循环来递归地从大型回归中删除最不重要的系数。

一切看起来都很好,直到 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 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。