我是第一次发布者,但是长期用户却在堆栈上溢出。另外,我是R的初学者,所以请裸身。我正在尝试使用具有4列的数据框(所有这些都是因变量)和具有194行和212列的数据框进行简单的线性回归分析。 我还有5个其他数据框用作相同分析的因变量
在我当前的代码中,我已经达到了预期的结果,但是我需要进行扩展,我试图添加一个额外的for循环(用于因变量的列),但是我还需要同时创建更多的空列表。
我想知道我将如何实现?
我当前的for循环是:
x <- data.frame(lagvar[1:175,c(-1,-2)])
out <- data.frame(NULL) # create object to keep results
for (i in 1:length(x)) {
m <- summary(lm(y[,1] ~ x[,i])) # run model
out[i, 1] <- names(x)[i] # print variable name
out[i, 2] <- m$coefficients[1,1] # intercept
out[i, 3] <- m$coefficients[2,1] # coefficient
out[i, 4] <-m$coefficients[2,4] # Pvalue
out[i,5] <-m$r.squared # R-squared
}
names(out) <- c("Variable", "Intercept", "Coefficient","P-val","R-square")
head(out)````
Giving the output
> head(out)
Variable Intercept Coefficient P-val R-square
1 GDP.SC 0.2540527 -4.722220e-07 0.7032087 8.411229e-04
2 GDP.SC1 0.1148311 3.107631e-07 0.7959237 3.899366e-04
3 GDP.SC2 0.1609010 4.998762e-08 0.9673014 9.855831e-06
4 GDP.SC3 0.1353608 1.959274e-07 0.8746321 1.468544e-04
5 GDP.SC4 0.1439931 1.487237e-07 0.9064221 8.200597e-05
6 CivilianLaborForce.SC 0.2595231 -4.078450e-08 0.7716514 4.881398e-04
>