Fit the model into groups using the Data.Table package

How can I map multiple models into groups using the data.table syntax? I want my output to be data.frame with columns for each "by group" and one column for each model. Currently, I can do this using the dplyr package, but I cannot do this in data.table.

# example data frame
df <- data.table(
   id = sample(c("id01", "id02", "id03"), N, TRUE),     
   v1 = sample(5, N, TRUE),                          
   v2 = sample(round(runif(100, max = 100), 4), N, TRUE) 
)

# equivalent code in dplyr
group_by(df, id) %>%
do( model1= lm(v1 ~v2, .),
    model2= lm(v2 ~v1, .)
  )

# attempt in data.table
df[, .(model1 = lm(v1~v2, .SD), model2 = lm(v2~v1, .SD) ), by = id ]

# Brodie G solution
df[, .(model1 = list(lm(v1~v2, .SD)), model2 = list(lm(v2~v1, .SD))), by = id ]
+4
source share
1 answer

Try:

df[, .(model1 = list(lm(v1~v2, .SD)), model2 = list(lm(v2~v1, .SD))), by = id ]

or a little more idiomatic:

formulas <- list(v1~v2, v2~v1)
df[, lapply(formulas, function(x) list(lm(x, data=.SD))), by=id]
+6
source

All Articles