Create and Call Linear Models from List
Asked Answered
D

3

3

So I'm trying to compare different linear models in order to determine if one is better than another. However I have several models, so I want to create an list of models and then call on them. Is that possible?

 Models <- list(lm(y~a),lm(y~b),lm(y~c)
 Models2 <- list(lm(y~a+b),lm(y~a+c),lm(y~b+c))

 anova(Models2[1],Models[1])

Thank you for your help!

Dolomite answered 7/8, 2013 at 15:54 Comment(3)
This may be of help.Toein
Does using anova(Models2[[1]],Models[[1]]) work?Hornback
Note that the anova is most useful for nested models.Janice
B
6

If you have two lists of models, and you want to compare each pair of models, then you want Map:

models1 <- list(lm(y ~ a), lm(y ~ b), lm(y ~ c)
models2 <- list(lm(y ~ a + b), lm(y ~ a + c), lm(y ~ b + c))

Map(anova, models1, models2)

This is basically equivalent to the following for loop:

out <- vector("list", length(models1))
for (i in seq_along(out) {
  out[[i]] <- anova(models1[[i]], models2[[i]])
}

Map is an example of a functional, and you can find out more about them at https://github.com/hadley/devtools/wiki/Functionals

Bertelli answered 7/8, 2013 at 17:5 Comment(0)
P
4

You can use do.call to convert a list of any length into a call suitable for a function taking .... The only trick here is that anova expects the first model to be named--that's what the Curry handles by creating a new function which already has its first argument specified.

Put everything except the first model (call it lm1) into one list called Models.

Then:

library(functional)
do.call( Curry(anova, object=lm1), Models )

Example:

> Models <- list( lm(runif(10)~rnorm(10)),lm(runif(10)~rnorm(10)),lm(runif(10)~rnorm(10)) )
> lm1 <- lm(runif(10)~rnorm(10))
> do.call( Curry(anova, object=lm1), Models )
Analysis of Variance Table

Model 1: runif(10) ~ rnorm(10)
Model 2: runif(10) ~ rnorm(10)
Model 3: runif(10) ~ rnorm(10)
Model 4: runif(10) ~ rnorm(10)
  Res.Df     RSS Df Sum of Sq F Pr(>F)
1      8 0.46614                      
2      8 0.59522  0  -0.12908         
3      8 1.00869  0  -0.41346         
4      8 0.81686  0   0.19182         
Pourpoint answered 7/8, 2013 at 16:3 Comment(3)
I am suprised too. Especially, because it doesn't work like that with AIC.Janice
Follow-up question to get to the bottom of this: #18108919Pourpoint
@Janice see here for a similar question with AIC.Jerejereld
H
1
x <- rnorm(100,0,1)
y <- rnorm(100,5,2)
z <- rnorm(100,8,1)    
models <- list(y.x = lm(y~x), y.z = lm(y~z))
anova(models[[1]],models[[2]])

This worked for me.

Hornback answered 7/8, 2013 at 16:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.