r - Working with rich objects in data.table columns -


say have data.table in 1 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))), = g] 

now want extract r-squared value each model. can better this?

models[, list(rsq = summary(mod[[1]])$r.squared), = g]  ##    g      rsq ## 1: 1 1.000000 ## 2: 2 1.000000 ## 3: 3 0.004452 

ideally, i'd able eliminate [[1]] , not rely on knowing previous grouping variable (i know want each row it's own group).

this summary being bad little function, that's not vectorized. how vectorizing manually (this same @mnel's solution):

r.squared = vectorize(function(x) summary(x)$r.squared)  models[, rsq := r.squared(mod)] models #   g  mod         rsq #1: 1 <lm> 1.000000000 #2: 2 <lm> 1.000000000 #3: 3 <lm> 0.004451631 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -