简体   繁体   中英

Loop with list of variables for multiple glm objects in R

I can not for the life of me see why this isn't working for me in R:(

## Unadjusted model 
noadj_var <- list("a",
                  "b",
                  "c",
                  "d",
                  )

for (i in 1:length(noadj_var)) {
  paste0("unadjusted_model_",i) <- glm(
    df$dependent_variable ~ i,
    data = df[df$present_2018 == "Yes" , ],
    family = binomial(link=logit),
    na.action = na.exclude
  )
}

I get the error:

Error in model.frame.default(formula = df$dependent_variable ~ i, data = df[df$present_2018 ==  : 
 variable lengths differ (found for 'i')

I don't understand why I get this error when I have na.action = na.exclude

Is there something else that is being messed up?

Just to preface this the variable names "a", "b", "c" are not the real names, and I can't just change them to a sequence, it needs to be a list of strings.

Another possibility with the purrr package:

 list("a",
       "b",
       "c",
       "d",
  ) %>% 
    purrr::set_names(paste0("unadjusted_model_", .)) %>% 
    purrr::map(~glm(reformulate(.x, 'dependent_variable'),data = df),
               family = binomial(link=logit),
               na.action = na.exclude ) %>% 
    purrr::map(broom::tidy)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM