I need to create a named list of linear models in R.
models=list()
for (tag in tagnames){
expr=paste0(tag," ~ .")
f=formula(expr)
models[tag]=lm(f,df)
}
This is the code that I wrote; it actually creates the list, but apparently it is a list of lists which are not callable objects (i.e., the method predict doesn't work on the elements of the list).
How can I make the element of the lists usable as actual lm objects?
You can create a list of your models with lapply:
models <- lapply(tagnames, function(x) lm(formula(paste0(x, " ~ .")), df))
and assign the names with
names(models) <- tagnames
Then call predict on the list element:
predict(models[["name"]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With