简体   繁体   English

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

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

I want to fit regression models using a single predictor variable at a time.我想一次使用一个预测变量来拟合回归模型。 In total I have 7 predictors and 1 response variable.我总共有 7 个预测变量和 1 个响应变量。 I want to write a chunk of code that picks a predictor variable from data frame and fits a model.我想编写一段代码,从数据框中选择一个预测变量并适合 model。 I would further want to extract regression coefficient( not the intercept) and the sign of it and store them in 2 vectors.我还想提取回归系数(不是截距)和它的符号,并将它们存储在 2 个向量中。 Here's my code-这是我的代码-

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))
}

Over here x in will use the first column, then the 2nd and so on.在这里 x in 将使用第一列,然后是第二列,依此类推。 However, I am getting the following error.但是,我收到以下错误。

Error in model.frame.default(formula = distance ~ FAA_unique_with_duration_filtered[x], : invalid type (list) for variable 'FAA_unique_with_duration_filtered[x]' model.frame.default 中的错误(公式 = 距离 ~ FAA_unique_with_duration_filtered[x],:变量“FAA_unique_with_duration_filtered[x]”的类型(列表)无效

Is there a way to do this using loops?有没有办法使用循环来做到这一点?

You don't really need loops for this.你真的不需要循环。

Suppose we want to regress y1, the 5th column of the built-in anscombe dataset, separately on each of the first 4 columns.假设我们要对内置 anscombe 数据集的第 5 列 y1 进行回归,分别在前 4 列中的每一列上进行回归。

Then:然后:

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)

Alternately the following where reg is either of the reg definitions above.或者以下其中 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