Is there a function that can extract two or more columns from a coeftest
object? This is easy one coeftest
object at a time, but can I do the same to a list (other than a for()
loop)?
> # 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
Maybe the more fundamental question is if there is a way to turn the meat of the coeftest
object into a data frame, which would allow me to extract columns singly, then use mapply()
. Thanks!
Edit: I would like to end up with a matrices (or data frames) with the first and second columns.
[[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
[[
is the wrong subset function in this case. Note that when you lapply()
over a list, what you are operating on are the components of the list, the bits you would get with list[[i]]
where i
is the ith component.
As such, you only need the [, 1:2]
bit of cts[[1]][, 1:2]
in the lapply()
call. It is a little bit trickier because of the arguments for [
, but easily doable with 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
Note the <space>,
before 1:2
; this is the equivalent of [ , 1:2]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With