nicholas
nicholas

Reputation: 983

How to get multiple regression models from a list of lists to a gtsummary table?

Given the following, how can I get the two models in out to a gtsummary table?

library(dplyr)
library(purrr)

m.1.1 <- "cyl"
m.1.2 <- paste(c(m.1.1, "disp"), collapse = " + ")

out <- map(dplyr::lst(m.1.1, m.1.2), 
           ~ lm(data = mtcars, formula = as.formula(paste0("mpg ~ ", .x))))

I think that I want to use tbl_regression and tbl_merge, but -- basing my code off of the answer to this question -- I cannot get it to work.

Upvotes: 2

Views: 1910

Answers (1)

Daniel D. Sjoberg
Daniel D. Sjoberg

Reputation: 11679

You are correct, you can use tbl_regression() and tbl_merge() to prepare the table. Example below!

library(gtsummary)
library(tidyverse)

tbl <- 
  c("cyl", "cyl + disp") %>%            # vector of covariates
  map(
    ~ paste("mpg", .x, sep = " ~ ") %>% # build character formula
      as.formula() %>%                  # convert to proper formula
      lm(data = mtcars) %>%             # build linear regression model
      tbl_regression()                  # display table with gtsummary
  ) %>%
  # merge tables into single table
  tbl_merge(
    tab_spanner = c("**Univariate**", "**Multivariable**")
  )

enter image description here Created on 2021-10-11 by the reprex package (v2.0.1)

Upvotes: 3

Related Questions