r - 如何使用 purrr 中的 map 和 dplyr 中的 mutate 来生成 glm 汇总表?

标签 r dplyr glm purrr

我正在使用包 purrr 和 broom 来生成一系列 glm 并构建一个包含模型信息的表格,以便我可以比较它们。

当我从 purrr 调用 map 函数时,代码失败。我认为问题与 mutate 和 map 的组合有关。我想为每个 glm 生成一个行,为 glm 的组件生成一个列。

数据与代码

library(broom)
library(tidyverse)

# Produce a dummy dataset
set.seed(123)
dummy <- tibble(ID = 1:50,
                A = sample(x = 1:200, size = 50, replace = T),
                B = as.factor(sample(x = c("day", "night"), size = 50, replace = T)),
                C = as.factor(sample(x = c("blue", "red", "green"), size = 50, replace = T)))

# Nest the data
nested <- dummy %>% select(-ID) %>% nest()

# Define a function for a generalized linear model with a poisson family
mod_f <- function(x, df = nested) {glm(formula = as.formula(x), family = poisson, data = df)}

# Make a list of formulas as a column in a new dataframe
# A is our response variable that we try to predict using B and C
formulas <- c("A ~ 1", "A ~ B", "A ~ C", "A ~ B + C")
tbl <- tibble(forms = formulas)

# Fit the glm's using each of the formulas from the formulas vector
tbl_2 <- tbl %>% mutate(mods = map(formulas, mod_f))
        #gla = mods %>% map(glance),
        #tid = mods %>% map(tidy),
        #aug = mods %>% map(augment),
        #AIC = gla %>% map_dbl("AIC"))

错误

Error in mutate_impl(.data, dots): Evaluation error: object 'A' not found

最佳答案

另一个 Stackoverflow 用户提供的最终答案:

library(broom)
library(tidyverse)

# Produce a dummy dataset
set.seed(123)
dummy <- tibble(ID = 1:50,
                A = sample(x = 1:200, size = 50, replace = T),
                B = as.factor(sample(x = c("day", "night"), size = 50, replace = T)),
                C = as.factor(sample(x = c("blue", "red", "green"), size = 50, replace = T)))

# Define a function for a generalized linear model with a poisson family
mod_f <- function(x) {glm(formula = as.formula(x), family = poisson, data = dummy)}

# Make a list of formulas as a column in a new dataframe
# A is yhe response variable we try to predict using B and C
formulas <- c("A ~ 1", "A ~ B", "A ~ C", "A ~ B + C")
tbl <- tibble(forms = formulas)

# Fit the glm using each of the formulas stored in the formulas vector
tbl_2 <- tbl %>% mutate(all = map(formulas, mod_f),
                        gla = all %>% map(glance),
                        tid = all %>% map(tidy),
                        aug = all %>% map(augment),
                        AIC = all%>% map_dbl("AIC"))

关于r - 如何使用 purrr 中的 map 和 dplyr 中的 mutate 来生成 glm 汇总表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53968490/

相关文章:

r - 如何按dplyr中的固定行数分组? [复制]

r - 函数 : argument "data" is missing, 内的 lapply、glm 和 speedglm 没有默认值

python - 使用python提取回归系数

r - Shiny 应用程序未在 Shinyapps.io 中运行(错误 : Object UI Not Found)

r - 如何将 LME4 输出提取到 latex 表?

r - 将图形分开打印到 PDF 文件并同时输出 R Markdown

R:带条件的向上计数器

R:查找顶部、中间和底部值以在 dplyr 中创建类别列

r - 避免在带有 bs() 项的模型公式中写入大量列名

javascript - 解析一个 JSON 字符串并显示它