从矩阵lm对象中提取摘要

时间:2015-10-03 18:49:48

标签: r matrix statistics linear-regression lm

我想从lm对象的摘要部分获取系数,除了我输入了一个矩阵,我对摘要部分变为null。这是我的代码:

n=12
y=rnorm(n,23,1)
x1=rnorm(n,23,1)
x2=rnorm(n,15.5,1)
lm1=lm(y~x1+x2)
n2=10
b0=4;b1=2;b2=3
sim1<-function(){
  randmat=matrix(rnorm(n*n2,0,8),n,n2)
  x1mat=matrix(x1,n,n2)
  x2mat=matrix(x2,n,n2)
  return(b0+b1*x1mat+b2*x2mat+randmat)
}
sim1=sim1()
lm1=lm(sim1~x1+x2)
c2=summary(lm1)$coefficients

> c2
NULL

我想要的是这个(但重复):

lm2=lm(sim1[,1]~x1+x2)
summary(lm2)$coefficients

有谁知道如何提取这些?感谢

-Rik

1 个答案:

答案 0 :(得分:1)

另一种方法是在代码的以下行结束后执行以下操作。

lm1=lm(sim1~x1+x2) #this runs 10 models

所有系数都将summary(lm1)列为Response Y1 ...存储到Response Y10(即10个模型,与ncol(sim1)一样多。)

为了从每个模型中获取系数,你可以做到:

all_coef <- lapply( paste0('Response Y', 1:ncol(sim1)),  
                    function(x) summary(lm1)[[x]]$coefficients)

或者正如@Rik在评论中提到的那样,如果你有一个大的矩阵,如果在lapply循环中没有重复summary(lm1),它会更快。

the_sum  <- summary(lm1)
all_coef <- lapply( paste0('Response Y', 1:ncol(sim1)),  
                    function(x) the_sum[[x]]$coefficients)

输出结果为:

> all_coef
[[1]]
              Estimate Std. Error   t value  Pr(>|t|)
(Intercept) 135.242552  80.136427  1.687654 0.1257496
x1           -4.777486   2.953534 -1.617549 0.1402142
x2            4.464435   3.891641  1.147186 0.2808857

[[2]]
               Estimate Std. Error     t value  Pr(>|t|)
(Intercept) 119.1772823 111.603046  1.06786765 0.3133851
x1           -0.1376013   4.113277 -0.03345297 0.9740435
x2           -1.2946027   5.419744 -0.23886785 0.8165585

[[3]]
              Estimate Std. Error    t value  Pr(>|t|)
(Intercept) -51.329923  63.495202 -0.8084063 0.4397018
x1            3.721227   2.340199  1.5901325 0.1462682
x2            3.793981   3.083498  1.2304147 0.2497304

[[4]]
               Estimate Std. Error     t value   Pr(>|t|)
(Intercept) 124.8606014  57.669842  2.16509352 0.05857967
x1           -1.2517705   2.125498 -0.58893044 0.57039201
x2           -0.1159803   2.800603 -0.04141263 0.96787111

#...and so on until 10

要获得模型的各个系数,请执行以下操作:

all_coef[[<the_number_you_want>]]