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!
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
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
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.
来源:https://stackoverflow.com/questions/18108045/create-and-call-linear-models-from-list