【问题标题】:fitting linear regression models with different predictors using loops使用循环拟合具有不同预测变量的线性回归模型
【发布时间】:2021-08-09 06:08:46
【问题描述】:

我想一次使用一个预测变量来拟合回归模型。我总共有 7 个预测变量和 1 个响应变量。我想编写一段代码,从数据框中选择一个预测变量并拟合一个模型。我还想提取回归系数(不是截距)和它的符号,并将它们存储在 2 个向量中。这是我的代码-

for (x in (1:7))
{
  
fit <- lm(distance ~ FAA_unique_with_duration_filtered[x] , data=FAA_unique_with_duration_filtered)
coeff_values<-summary(fit)$coefficients[,1]
coeff_value<-coeff_values[2]
append(coeff_value_vector,coeff_value , after = length(coeff_value_vector))
append(RCs_sign_vector ,sign(coeff_values[2]) , after = length(RCs_sign_vector))
}

这里 x in 将使用第一列,然后是第二列,依此类推。但是,我收到以下错误。

model.frame.default 中的错误(公式 = 距离 ~ FAA_unique_with_duration_filtered[x],: 变量“FAA_unique_with_duration_filtered[x]”的类型(列表)无效

有没有办法使用循环来做到这一点?

【问题讨论】:

    标签: r loops vector regression linear-regression


    【解决方案1】:

    你真的不需要循环。

    假设我们要对内置 anscombe 数据集的第 5 列 y1 分别回归前 4 列。

    然后:

    a <- anscombe
    reg <- function(i) coef(lm(y1 ~., a[c(5, i)]))[[2]] # use lm
    coefs <- sapply(1:4, reg)
    signs <- sign(coefs)
    
    # or
    
    a <- anscombe
    reg <- function(i) cov(a$y1, a[[i]]) / var(a[[i]]) # use formula for slope
    coefs <- sapply(1:4, reg)
    signs <- sign(coefs)
    

    或者以下,其中 reg 是上述任何一个 reg 定义。

    a <- anscombe
    coefs <- numeric(4)
    for(i in 1:4) coefs[i] <- reg(i)
    signs <- sign(coefs)
    

    【讨论】:

    • 最后一个选择使用for 循环。
    猜你喜欢
    • 2018-03-17
    • 2020-12-21
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 2021-07-22
    相关资源
    最近更新 更多