首页 > 解决方案 > 将矩阵与 R 中的列向量进行回归

问题描述

我正在尝试根据单个列向量(自变量)回归矩阵的每一列(因变量),并存储系数和残差。到目前为止,这是一个示例数据和我的代码:

gwthRatesAllCities06To08 <- matrix(1:60, nrow = 4, ncol = 15)
natGwthRates06To08 <- c(2,1,3,5)

for (i in 1 : ncol(gwthRatesAllCities06To08)) {
OLSEst[[i]]<- lm(formula = gwthRatesAllCities06To08[,i] ~ natGwthRates06To08)
}

但是,上面的代码没有给我我想要的,你能帮我找出原因吗?提前谢谢了!

标签: rfor-looplm

解决方案


lm可以在同一右手边回归多个 Y 向量。只需将左侧指定为一个矩阵,其列是 Y 向量。

y <- matrix(1:60, nrow = 4, ncol = 15)
x <- c(2,1,3,5)

fm <- lm(y ~ x)

coef(fm) # the 15 columns of coef are the 15 sets of coefficients
resid(fm) # the 15 columns of resid are the 15 sets of residuals

推荐阅读