【发布时间】:2020-08-25 11:00:29
【问题描述】:
假设在 R 中我有来自多个 glm() 函数调用的多个 GLM 对象。
glm_01
glm_02
...
glm_nn
...假设我想使用卡方或 F ANOVA 检验进行所有可能的成对比较。
anova(glm_01, glm_02, test = "F")
anova(glm_01, glm_03, test = "F")
anova(glm_01, glm_04, test = "F")
...
我不想手动执行此操作,因为模型列表很长。相反,我想获取相关模型对象的列表(以"glm_" 开头的任何内容)并自动进行所有成对比较。但是我不确定如何将模型对象(而不是字符串形式的名称)传递给 anova() 函数。
举个简单的例子:
data(mtcars)
# create some models
glm_01 <- glm(mpg ~ cyl , mtcars, family = gaussian())
glm_02 <- glm(mpg ~ cyl + disp , mtcars, family = gaussian())
glm_03 <- glm(mpg ~ cyl + disp + hp , mtcars, family = gaussian())
glm_04 <- glm(mpg ~ cyl + disp + hp + wt, mtcars, family = gaussian())
# get list of relevant model objects from the R environment
model_list <- ls()
model_list <- model_list[substr(model_list, 1, 4) == "glm_"]
# create a table to store the pairwise ANOVA results
n_models <- length(model_list)
anova_table <- matrix(0, nrow = n_models, ncol = n_models)
# loop through twice and do pairwise comparisons
for(row_index in 1:n_models) {
for(col_index in 1:n_models) {
anova_table[row_index, col_index] <- anova(model_list[row_index], model_list[col_index], test = "F")$'Pr(>F)'[2]
}
}
...但是最后这个循环当然不起作用,因为我没有将模型对象传递给anova(),而是将对象的名称作为字符串传递。如何告诉anova() 使用字符串引用的对象,而不是字符串本身?
谢谢。
=======================
可能的解决方案:
data(mtcars)
glm_list <- list()
glm_list$glm_01 <- glm(mpg ~ cyl , mtcars, family = gaussian())
glm_list$glm_02 <- glm(mpg ~ cyl + disp , mtcars, family = gaussian())
glm_list$glm_03 <- glm(mpg ~ cyl + disp + hp , mtcars, family = gaussian())
glm_list$glm_04 <- glm(mpg ~ cyl + disp + hp + wt, mtcars, family = gaussian())
# create a table to store the pairwise ANOVA results
n_models <- length(glm_list)
anova_table <- matrix(0, nrow = n_models, ncol = n_models)
# loop through twice and do pairwise comparisons
row_idx <- 0
col_idx <- 0
for(row_glm in glm_list)
{
row_idx <- row_idx + 1
for(col_glm in glm_list)
{
col_idx <- col_idx + 1
anova_table[row_idx, col_idx] <- anova(row_glm, col_glm, test = "F")$'Pr(>F)'[2]
}
col_idx <- 0
}
row_idx <- 0
【问题讨论】:
-
如果您只是将所有模型放在一个列表中开始,这会容易得多。然后,您可以使用列表索引对它们进行迭代。
-
哦……我没想到。玩过代码并编辑了我的帖子以显示可能的解决方案(有点笨拙但似乎有效)。谢谢。