[R] store list objects in data.table
Rui Barradas
ru|pb@rr@d@@ @end|ng |rom @@po@pt
Sun Sep 22 00:33:53 CEST 2024
Às 22:25 de 21/09/2024, Naresh Gurbuxani escreveu:
> I am trying to store regression objects in a data.table
>
> df <- data.frame(x = rnorm(20))
> df[, "y"] <- with(df, x + 0.1 * x^2 + 0.2 * rnorm(20))
>
> mydt <- data.table(mypower = c(1, 2), myreg = list(lm(y ~ x, data = df),
> lm(y ~ x + I(x^2), data = df)))
>
> mydt
> # mypower myreg
> # <num> <list>
> #1: 1 <lm[12]>
> #2: 2 <lm[12]>
>
> But mydt[1, 2] has only the coeffients of the first regression. mydt[2,
> 2] has residuals of the first regression. These are the first two
> components of "lm" object.
>
> mydt[1, myreg[[1]]]
> #(Intercept) x
> # 0.107245 1.034110
>
> Is there a way to put full "lm" object in each row?
>
> Thanks,
> Naresh
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> https://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
Hello,
Yes, there are ways of pulling the full lm objects from the list column.
It's a matter of using the right indexing.
mydt[[2L]][1L] extracts a list whose element is a lm object.
mydt[[2L]][[1L]] extracts yhe lm object, this is the one you want.
See the two examples below.
library(data.table)
df <- data.frame(x = rnorm(20))
df[, "y"] <- with(df, x + 0.1 * x^2 + 0.2 * rnorm(20))
mydt <- data.table(
mypower = c(1, 2),
myreg = list(lm(y ~ x, data = df),
lm(y ~ x + I(x^2), data = df)))
mydt[[2L]][1L] |> class()
#> [1] "list"
mydt[[2L]][[1L]] |> class()
#> [1] "lm"
Hope this helps,
Rui Barradas
--
Este e-mail foi analisado pelo software antivírus AVG para verificar a presença de vírus.
www.avg.com
More information about the R-help
mailing list