Create and Call Linear Models from List

烂漫一生 提交于 2019-11-28 09:31:33

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!