从coeftest对象列表中提取列

Ric*_*ron 7 r lapply

是否有可以从coeftest对象中提取两个或更多列的函数?这一个coeftest对象很容易,但我可以对列表(for()循环除外)做同样的事情吗?

> # meaningless data
> temp <- data.frame(a = rnorm(100, mean = 5), b = rnorm(100, mean = 1),
+                    c = 1:100)
> formulas <- list(a ~ b, a ~ c)
> models <- lapply(formulas, lm, data = temp)
> library(lmtest)
> cts <- lapply(models, coeftest)

> # easy to extract columns one object at a time
> cts[[1]][, 1:2]
              Estimate Std. Error
(Intercept)  5.0314196  0.1333705
b           -0.1039264  0.0987044

> # but more difficult algorithmically
> # either one column
> lapply(cts, "[[", 1)
[[1]]
[1] 5.03142

[[2]]
[1] 5.312007

> # or two
> lapply(cts, "[[", 1:2)
Error in FUN(X[[1L]], ...) : attempt to select more than one element
Run Code Online (Sandbox Code Playgroud)

也许更基本的问题是,如果有办法将coeftest对象的肉变成数据框,这将允许我单独提取列,然后使用mapply().谢谢!

编辑:我想最后得到第一列和第二列的矩阵(或数据帧).

    [[1]]
              Estimate Std. Error
(Intercept)  5.0314196  0.1333705
b           -0.1039264  0.0987044

[[2]]
                Estimate  Std. Error
(Intercept)  5.312007153 0.199485363
c           -0.007378529 0.003429477
Run Code Online (Sandbox Code Playgroud)

Rei*_*son 12

[[在这种情况下是错误的子集函数.需要注意的是,当你lapply()在一个列表,你在操作什么是列表的组件,你会用得到位list[[i]],其中i为第i种成分.

因此,您只需要在[, 1:2]cts[[1]][, 1:2]lapply()电话.这有点棘手,因为有争议[,但很容易做到lapply():

> lapply(cts, `[`, , 1:2)
[[1]]
                Estimate Std. Error
(Intercept)  4.926679544  0.1549482
b           -0.001967657  0.1062437

[[2]]
               Estimate  Std. Error
(Intercept) 4.849041327 0.204342067
c           0.001494454 0.003512972
Run Code Online (Sandbox Code Playgroud)

注意<space>,之前1:2; 这相当于[ , 1:2].


koh*_*ske 5

我不确定这是不是你想要的,但是怎么样:

> do.call("rbind", cts)[, 1:2]
                 Estimate  Std. Error
(Intercept)  4.8200993881 0.142381642
b           -0.0421189130 0.092620363
(Intercept)  4.7459340076 0.206372906
c            0.0005770324 0.003547885
Run Code Online (Sandbox Code Playgroud)