繁体   English   中英

使用循环拟合具有不同预测变量的线性回归模型

[英]fitting linear regression models with different predictors using loops

我想一次使用一个预测变量来拟合回归模型。 我总共有 7 个预测变量和 1 个响应变量。 我想编写一段代码,从数据框中选择一个预测变量并适合 model。 我还想提取回归系数(不是截距)和它的符号,并将它们存储在 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]”的类型(列表)无效

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

你真的不需要循环。

假设我们要对内置 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM