使用循环拟合具有不同预测变量的线性回归模型
fitting linear regression models with different predictors using loops
我想一次使用一个预测变量来拟合回归模型。我总共有 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]'
的无效类型(列表)
有没有办法使用循环来做到这一点?
你真的不需要循环。
假设我们要回归 y1,内置 anscombe 数据集的第 5 列,分别在前 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)
我想一次使用一个预测变量来拟合回归模型。我总共有 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]'
的无效类型(列表)有没有办法使用循环来做到这一点?
你真的不需要循环。
假设我们要回归 y1,内置 anscombe 数据集的第 5 列,分别在前 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)