如何使用 purrr 中的映射和 dplyr 中的 mutate 来生成 glm 汇总表?

2023-12-24

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

当我从 purrr 调用地图函数时,代码失败。我认为问题与 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

mutate_impl(.data,dots) 中的错误:评估错误:找不到对象“A”


另一位 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"))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 purrr 中的映射和 dplyr 中的 mutate 来生成 glm 汇总表? 的相关文章

随机推荐