r - 创建数据框列表,显示嵌套模型列表中的 AICc 值

标签 r list lapply

我有一个统计模型列表:

###Data import
Responses <- as.data.frame(matrix(sample(0:10, 1*100, replace=TRUE), ncol=2))
colnames(Responses) <- c("A","B")
Explanatories <- as.data.frame(matrix(sample(20:30, 1*100, replace=TRUE), ncol=2))
colnames(Explanatories) <- c("x","y")

###Create models
Models <- list(
lm(Responses$A ~ Explanatories$x),
lm(Responses$B ~ log10(Explanatories$x)),
lm(Responses$B ~ exp(Explanatories$y))
)

以及空模型列表。这些对应于前面列表中的模型,因此例如我想将“Models”中的第一个 lm 与“Models_null”中的第一个 lm 进行比较:

Models_null <- list(
lm(Responses$A ~ 1),
lm(Responses$B ~ 1),
lm(Responses$B ~ 1)
)

All_models <- list(Models,Models_null)
names(All_models)<-c("full","res")

我想使用以下公式计算每个模型的 AICc 分数:

aicc<-function(x) AIC(x)+((2*length(coef(x))*(length(coef(x))+1))/(length(resid(x))-length(coef(x))-1))

我需要根据 AICc 分数在每个完整模型和空模型之间的比较进行一些计算。 所以我需要的是一个数据框列表,显示每对模型的 AICc 分数,其中 2 列表示“完整”和“空”。预先感谢您对此提供的任何帮助。

最佳答案

这是一个双重sapply:

sapply(All_models, sapply, aicc)
#          full      res
# [1,] 267.4959 266.0534
# [2,] 251.9809 251.9127
# [3,] 253.5760 251.9127

第一个sapply仅遍历ModelsModels_null。然后自然地,对于这两个列表中的每一个,我们再次希望应用 sapply,其中对于每个模型,我们将使用 aicc。这正是 @Rui Barradas 的解决方案,只需一行。

如果需要,当然,之后结果可以转换为数据帧。


要获取一个其元素是上述矩阵的行的列表,以下三个中的任何一个都可以:

lapply(seq_along(Models), function(i) 
  data.frame(full = aicc(Models[[i]]), null = aicc(Models_null[[i]])))

Map(data.frame, full = lapply(Models, aicc), null = lapply(Models_null, aicc))

do.call(Map, c(data.frame, lapply(All_models, sapply, aicc)))

关于r - 创建数据框列表,显示嵌套模型列表中的 AICc 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53673329/

相关文章:

r - 使用 .SD 计算 data.table 中列子集的累积和

r - 将 n 个 *表达式* 的列表应用于数据帧的每一行?

r - 在 R 中的嵌套数据框中多次调用 ifelse

R将EXIF数据写入JPEG文件

r - 查找多个组的最后一行

R文本挖掘包: Allowing to incorporate new documents into an existing corpus

python - Python 中的嵌套列表排序

list - Flutter:可重新排序和动画 ListView - 知道吗?

list - 在 Lisp 中替换列表小节的最惯用方法

r - R Commander 中 S_Dbw 输出中的 "Inf"是什么意思?