I have a straight-forward question about logistic regression in R.
I have a binary response variable y, and let's say 20 predictors (x1-x20). I would like to fit logistic regression model y~x for each x one at a time (so in this case there would be 20 models), and save the coefficients, odds ratio, or p-values in a table.
I notice that there are ols_step_all_possible(model, ...) function that does similar thing, but not sure if it works for logistic regression. There is also dredge function in MuMIn package but I really just need the "one-variable" models.
Can someone please shed some light? Thank you in advance!
There are many answers of this form.
library(tidyverse)
library(broom)
varnames <- paste0("x", 1:20)
names(varnames) <- varnames ## seems weird, but for .id = below
res <- (varnames
|> map(\(.x) reformulate(.x, response = "respvar"))
|> map(\(.f) glm(.f, data = my_data, family = "binomial")
|> map_dfr(tidy, .id = "predvar")
)
Other people prefer nest
/unnest
/list-column solutions, but I have trouble getting my head around them. You can also do this perfectly well with base-R for
loops.