Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lapply on a list of models

Tags:

r

lapply

I have generated a list of models, and would like to create a summary table.

As and example, here are two models:

x <- seq(1:10)
y <- sin(x)^2
model1 <- lm(y ~ x)
model2 <- lm(y ~ x + I(x^2) + I(x^3))

and two formulas, the first generating the equation from components of formula

get.model.equation <- function(x) {
  x <- as.character((x$call)$formula)
  x <- paste(x[2],x[1],x[3])
}

and the second generating the name of model as a string

get.model.name <- function(x) {
  x <- deparse(substitute(x))
}

With these, I create a summary table

model.list <- list(model1, model2)
AIC.data <- lapply(X = model.list, FUN = AIC)
AIC.data <- as.numeric(AIC.data)
model.models <- lapply(X = model.list, FUN = get.model)
model.summary <- cbind(model.models, AIC.data)
model.summary <- as.data.frame(model.summary)
names(model.summary) <- c("Model", "AIC")
model.summary$AIC <- unlist(model.summary$AIC)
rm(AIC.data)
model.summary[order(model.summary$AIC),]

Which all works fine. I'd like to add the model name to the table using get.model.name

x <- get.model.name(model1)

Which gives me "model1" as I want.

So now I apply the function to the list of models

model.names <- lapply(X = model.list, FUN = get.model.name)

but now instead of model1 I get X[[1L]]

How do I get model1 rather than X[[1L]]?

I'm after a table that looks like this:

 Model                Formula       AIC
model1                  y ~ x  11.89136
model2 y ~ x + I(x^2) + I(x^3) 15.03888
like image 964
Isaiah Avatar asked Sep 02 '25 06:09

Isaiah


1 Answers

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)
like image 129
baptiste Avatar answered Sep 04 '25 19:09

baptiste