Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

r - Create and Call Linear Models from List

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...