R中具有多个因变量和自变量的线性回归

Linear regression with several dependent and independent variables in R

我希望在 R 中进行线性回归,以模拟 5 个自变量对 376 列数据的影响。

我有一个名为 'dd' 的大矩阵(541 行和 402 列),我只想插入矩阵中的某些列作为回归中的 IV 和 DV。从 dd 开始,我想要 376 个特定的列来形成我的 DV 和 5 个列来形成我的 IV。我使用每列的名称(例如 'column_42')作为索引,分别用于 IV 和 DV:

IVind=paste0('column_',c(4,14,15,24,43)) #index for IV

DVind=paste0('column_',c(10:13, 17:18, 26, 28, 49:54, 58, 60, 1001:1180, 2001:2180)) #index for DV

IV <-(dd[,IVind]) #save independent variables in 'IV'
DV <-(dd[,DVind]) #save independent variables in 'DV'

我试过像这样将 IV 和 DV 插入线性回归中:

try <- lm(DV~IV)

但收到以下错误:[[<-.data.frame(*tmp*, i, value = c(2113L, 2031L, 1971L, 中出错: 替换有 203040 行,数据有 540

有什么方法可以绕过这个错误吗?我了解这可能是因为我的 IV 和 DV 被保存在不同的矩阵中?

我尝试在回归函数中直接索引 dd:

lm(dd[,DVind]~dd[,IVind])

只收到同样的错误。

非常感谢任何帮助,谢谢!

对于多元响应,您需要提供一个矩阵:

dd = data.frame(matrix(rnorm(2180*1000),ncol=2180))
colnames(dd) = paste0("column_",1:ncol(dd))

IVind=paste0('column_',c(4,14,15,24,43)) #index for IV
DVind=paste0('column_',c(10:13, 17:18, 26, 28, 49:54, 58, 60, 1001:1180, 2001:2180))

IV <-as.matrix(dd[,IVind]) #save independent variables in 'IV'
DV <-as.matrix(dd[,DVind]) #save independent variables in 'DV'

fit= lm(IV~DV)

如果您想要更好看的系数,我们在左侧使用 cbind 以“,”分隔指定因变量。然后我们将数据子集化为您感兴趣的因变量/自变量:

LHS = paste("cbind(",paste(IVind,collapse=","),")")
print(LHS)
"cbind( column_4,column_14,column_15,column_24,column_43 )"

FORM = as.formula(paste(LHS,"~."))
print(FORM)
"cbind(column_4, column_14, column_15, column_24, column_43) ~ ."

fit = lm(FORM,data=dd[,c(IVind,DVind)])

head(fit$coefficients)
               column_4    column_14    column_15    column_24
(Intercept)  0.04386386 -0.044541800  0.005439126  0.033074816
column_10   -0.01849133  0.041040752  0.015390150  0.019472339
column_11   -0.05201253 -0.004719325  0.052012943 -0.027946384
column_12   -0.01194646 -0.063251091  0.017792048  0.004709211
column_13    0.15284270 -0.097150447 -0.038294054  0.003509769
column_17   -0.03693076  0.025828749 -0.039618893  0.023351389
               column_43
(Intercept)  0.003076990
column_10   -0.092318249
column_11   -0.049421542
column_12   -0.065078169
column_13   -0.013206731
column_17    0.006969634