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
679 views
in Technique[技术] by (71.8m points)

r - Using lapply on a list of models

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
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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)

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

...