Say I have a data.table in which one column contains linear models:
library(data.table)
set.seed(1014)
dt <- data.table(
g = c(1, 1, 2, 2, 3, 3, 3),
x = runif(7),
y = runif(7)
)
models <- dt[, list(mod = list(lm(y ~ x, data = .SD))), by = g]
Now I want to extract the r-squared value from each model. Can I do better than this?
models[, list(rsq = summary(mod[[1]])$r.squared), by = g]
## g rsq
## 1: 1 1.000000
## 2: 2 1.000000
## 3: 3 0.004452
Ideally, I'd like to be able to eliminate the [[1]]
and not rely on
knowing the previous grouping variable (I know I want each row to be
it's own group).