Reputation: 15691
I have a bunch of models I want to use through GLM, so I want to put them in a list, and loop through the list. However, the following codes draws an error:
m1<- glm(target~total+tot_eit_h_h1+tot_both_h_h1, data=data, family='binomial')
m2<- glm(target~total+tot_both_h_h1, data=data, family='binomial')
models<- c(m1,m2)
This works perfectly:
predictions <- predict(m1, data, type='response')
This code draws an error:
predictions <- predict(models[1], data, type='response')
Error in UseMethod("predict") :
no applicable method for 'predict' applied to an object of class "list"
Upvotes: 3
Views: 2666
Reputation: 15458
You can use Map
function with the trick as follows (example illustrated with mtcars data):
dep<-list("mpg~","mpg~") # list of dep variables which is same in both models
indep<-list("cyl","cyl+disp") #for model 1 includes cyl and for model 2 includes cyl and disp
prediction<-Map(function(x,y) predict(lm(as.formula(paste(x,y)),data=mtcars)),dep,indep)
> prediction[[1]]
Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout
20.62984 20.62984 26.38142 20.62984 14.87826
Valiant Duster 360 Merc 240D Merc 230 Merc 280
20.62984 14.87826 26.38142 26.38142 20.62984
Merc 280C Merc 450SE Merc 450SL Merc 450SLC Cadillac Fleetwood
20.62984 14.87826 14.87826 14.87826 14.87826
Lincoln Continental Chrysler Imperial Fiat 128 Honda Civic Toyota Corolla
14.87826 14.87826 26.38142 26.38142 26.38142
Toyota Corona Dodge Challenger AMC Javelin Camaro Z28 Pontiac Firebird
26.38142 14.87826 14.87826 14.87826 14.87826
Fiat X1-9 Porsche 914-2 Lotus Europa Ford Pantera L Ferrari Dino
26.38142 26.38142 26.38142 14.87826 20.62984
Maserati Bora Volvo 142E
14.87826 26.38142
Upvotes: 3
Reputation: 16607
Try
models<- list(m1,m2)
and
predictions <- predict(models[[1]], data, type='response')
glm
returns a list. The c
operator 'flattens' that list into a vector, so that the functions associated with glm
objects won't work on the flattened vector. As a rule, you don't want to use c
to concatenate lists (even if you can sometimes get away with it, as in your example).
Upvotes: 4