Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list of linear models in R?

Tags:

list

r

lm

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?

like image 785
lapally Avatar asked Dec 05 '25 05:12

lapally


1 Answers

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"]])
like image 178
LAP Avatar answered Dec 07 '25 22:12

LAP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!