Using lapply on a list of models

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-29 11:47:21

Do you want something like this?

model.list <- list(model1 = lm(y ~ x), 
                   model2 = lm(y ~ x + I(x^2) + I(x^3)))
sapply(X = model.list, FUN = AIC)

I'd do something like this:

model.list <- list(model1 = lm(y ~ x),
                   model2 = lm(y ~ x + I(x^2) + I(x^3)))
# changed Reduce('rbind', ...) to do.call(rbind, ...) (Hadley's comment)
do.call(rbind, 
        lapply(names(model.list), function(x) 
          data.frame(model = x, 
          formula = get.model.equation(model.list[[x]]), 
          AIC = AIC(model.list[[x]])
          )
        )
      )

#    model                 formula      AIC
# 1 model1                   y ~ x 11.89136
# 2 model2 y ~ x + I(x^2) + I(x^3) 15.03888

Another option, with ldply, but see hadley's comment below for a more efficient use of ldply:

 # prepare data
    x <- seq(1:10)
    y <- sin(x)^2
    dat <- data.frame(x,y)

# create list of named models obviously these are not suited to the data here, just to make the workflow work...
models <- list(model1=lm(y~x, data = dat), 
               model2=lm(y~I(1/x), data=dat),
               model3=lm(y ~ log(x), data = dat),
               model4=nls(y ~ I(1/x*a) + b*x, data = dat, start = list(a = 1, b = 1)), 
               model5=nls(y ~ (a + b*log(x)), data=dat, start = setNames(coef(lm(y ~ log(x), data=dat)), c("a", "b"))),
               model6=nls(y ~ I(exp(1)^(a + b * x)), data=dat, start = list(a=0,b=0)),
               model7=nls(y ~ I(1/x*a)+b, data=dat, start = list(a=1,b=1))
)

library(plyr)
library(AICcmodavg) # for small sample sizes
# build table with model names, function, AIC and AICc
data.frame(cbind(ldply(models, function(x) cbind(AICc = AICc(x), AIC = AIC(x))), 
                 model = sapply(1:length(models), function(x) deparse(formula(models[[x]])))
                      ))

     .id     AICc      AIC                     model
1 model1 15.89136 11.89136                     y ~ x
2 model2 15.78480 11.78480                y ~ I(1/x)
3 model3 15.80406 11.80406                y ~ log(x)
4 model4 16.62157 12.62157    y ~ I(1/x * a) + b * x
5 model5 15.80406 11.80406      y ~ (a + b * log(x))
6 model6 15.88937 11.88937 y ~ I(exp(1)^(a + b * x))
7 model7 15.78480 11.78480        y ~ I(1/x * a) + b

It's not immediately obvious to me how to replace the .id with a column name in the ldply function, any tips?

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