【问题标题】:As.formula does not work in loop? (adjusting regression)As.formula 不能循环工作? (调整回归)
【发布时间】:2021-05-12 08:49:44
【问题描述】:

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

在 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[,1]), , drop = FALSE])
  reg.equation <-as.formula(paste(least.significant, collapse = "-" ))
  reg <- update(reg, reg.equation)
  coeff <- data.frame(summary(reg)$coefficients[,4, , drop = FALSE])
}

【问题讨论】:

    标签: r statistics regression


    【解决方案1】:

    请提供数据与您的问题。如果没有可重现的示例,有时很难猜测发生了什么,但我认为以下内容可以说明问题。

    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[,1]), , drop = FALSE])
      reg.equation <-as.formula(paste(least.significant, collapse = "-" ))
      reg <- update(reg, reg.equation)
      coeff <- data.frame(summary(reg)$coefficients[,4, , drop = FALSE])
    }
    

    类(ff)中的错误

    注意,第一步中的least.significant"disp:hp",不能强制转换成公式:

    as.formula("disp:hp")
    as.formula("disp:hp + hp")
    

    等,但as.formula("~ disp:hp") 会起作用。有一个有用的函数,reformulate,它接受术语和响应的字符向量,因此在下面的示例中,您只需更改 reg.equation &lt;- 行即可:

    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[,1]), , drop = FALSE])
      reg.equation <- reformulate(setdiff(names(coef(reg)[-1]), least.significant), '.')
      reg <- update(reg, reg.equation)
      coeff <- data.frame(summary(reg)$coefficients[, 4, drop = FALSE])
    }
    coef(reg)
    # (Intercept)         cyl        disp    cyl:disp 
    # 49.03721186 -3.40524372 -0.14552575  0.01585388 
    

    【讨论】:

      猜你喜欢
      • 2016-12-21
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      • 2016-10-10
      • 2017-12-12
      • 2014-02-07
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多