Following some great questions like this one:
Why is using update on a lm inside a grouped data.table losing its model data?, I'm running regression within a data.table
and storing it, as the following:
DT = data.table(iris)
fit = DT[, list(list(lm(Sepal.Length ~ Sepal.Width + Petal.Length))), by = Species]
However, I would like to store the .J
output as lm
object lm output, and not as a data.table:
class(fit[Species=="setosa"])
#i would like fit to contain 3 lm objects, not data.tables!
# [1] "data.table" "data.frame"
My question is, how can I store within fit
3 lm objects and not 3 data tables, the reason I need that, is that I want to further use fit
for out sample prediction (using predict.lm
)?
For example, I would like to store within the data table an element of the following type:
model<-lm(Sepal.Length ~ Sepal.Width + Petal.Length,data=DT[Species=="setosa"])
class(model)
# [1] "lm"
#i would like the first element of fit to inclide model -> the model output object
new_data<-DT #just a toy example :) this isnt really the new data
predict(model,new_data)