Let's 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]
#
#
#
#
Ideally, I would like to remove [[1]]and not rely on knowing the previous grouping variable (I know that I want each line to be its own group).
source
share