loess()
returns an S3 object of class loess
. Internally these objects are represented as lists, what you can see if you call str()
on them.
Now there are mainly two reasons why your solutions fails:
In the for loop, you concatenate these objects (read here lists) with
c()
which simply concatenates the list elements (or object fields) to one larger list, resulting in an invalid object of classloess
. Then you try to save this list as column in yourdata.table
.I don't see why you would want to store the models in the end in a
data.table
, but I am almost sure, that this can't be done, since the column elements must be (as far as I remember) atomic vectors or lists. I'd rather store the models in a named list and leave them there.
Solution using base R
model <- list()
for( i in unique(dt$z) ){
model[[i]] <- loess(y ~ x, data = dt[ z==i ] )
}
Solution using plyr
library("plyr")
model <- dlply( df, "z", function(data){
loess( y ~ x, data = data )
} )
Or even shorter:
library("plyr")
model <- dlply( df, "z", loess, formula = quote(y ~ x) )
The latter two solutions can be applied on both: data.table
and data.frame
, but you don't take any advantages of the data.table
in this case. So you have to decide what is faster and less error-prone in the end.
In all three cases you can call
predict( model[["a"]], newdata = 2.5)
[1] 8.5