Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
349 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...