Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recovering lm() results from a data.table groupby models

I need to analyse the output of a series of lm() output from a data.table group_by regressions:

library(data.table)
x <- c(1:5,66:70,101:110) 
y <- 31:50
g <- c( 1,1,1,1,1,1,1,1,1,1          
       ,2,2,2,2,2,2,2,2,2,2)

dt <- data.table(x,y,g)
mod <- dt[ , .(model = .(lm(x~y, .SD)))
           , by = g]

mod has the correct models for each group g. Now I want to create a column with the residuals vector for each group g:

mod[, resi := residuals(model)
    , by = g]

It seems to run correctly, but the nem column resi was not created:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> mod
       g    model
   <num>   <list>
1:     1 <lm[12]>
2:     2 <lm[12]>

Why does this not work?

>Solution :

The problem is that you are applying residuals() to list(model) instead of directly to the model object.

mod[, resi := .(list(residuals(model[[1]])))
    , by = g]

# Or 

mod[, resi := lapply(model, residuals)]

#        g    model                                                                                    resi
#    <num>   <list>                                                                                  <list>
# 1:     1 <lm[12]>                    10.909091,  1.818182, -7.272727,-16.363636,-25.454545, 25.454545,...
# 2:     2 <lm[12]> -1.471465e-14, 6.482041e-15, 5.472051e-15, 4.101520e-15, 2.842011e-15, 1.526991e-15,...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading