在模型列表上使用lapply [英] 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),]
一切正常. 我想使用get.model.name
Which all works fine. I'd like to add the model name to the table using get.model.name
x <- get.model.name(model1)
哪一个我愿意给我"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)
但是现在我得到的是 X [[1L]]
如何获取 model1 而不是 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
推荐答案
您想要这样的东西吗?
model.list <- list(model1 = lm(y ~ x),
model2 = lm(y ~ x + I(x^2) + I(x^3)))
sapply(X = model.list, FUN = AIC)
这篇关于在模型列表上使用lapply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!