Input purrr derived list into tab_model in r

Viewed 125

I would like to create a table of linear models with all independent variables at the top, and all dependent variables on the left side. This can be done using the tab_model function of the sjPlot package: https://cran.r-project.org/web/packages/sjPlot/vignettes/tab_model_estimates.html.

While the documentation specifies how to get a multi-model table from inputting each model one-by-one (m1, m2, m3 etc), what I have is a purr-derived list of linear models. I searched the documentation and online forums but can't find anything on how to do this. This is an example:

library(sjPlot)
library(sjmisc)
library(sjlabelled)
library(tidyverse)

df <- data.frame(study_id = c(1:20),
                 leptin = runif(20),
                 insulin = runif(20),
                 gene1 = runif(20),
                 gene2 = runif(20),
                 age = runif(20, min = 20, max = 45),
                 sex = sample(c(0,1), size = 20, replace = TRUE))

model_function_covariates_for_table <- function(x,y) {
  M1 <- paste0(x, "~", y, "+ age + sex")
  M1_fit <- lm(M1, data = df)
  return(M1_fit)
}

bioactives <- names(df)[c(2:3)]
genes <- names(df)[c(4:5)]

bioactives <- purrr::set_names(bioactives)
genes <- purrr::set_names(genes)

# Works
m <- model_function_covariates_for_table("leptin", "gene1")

tab_model(m)

# Doesn't work
m <- map(bioactives,
         ~map(genes, model_function_covariates_for_table, y = .x))

tab_model(m)

Error message:

Error in if (fam.info$is_linear) transform <- NULL else transform <- "exp" : 
  argument is of length zero
In addition: Warning message:
Could not access model information.

Thanks in advance for any advice.

1 Answers

Here we need map2 as we are passing the corresponding elements of 'bioactives' and 'genes' into the function model_function_covariates_for_table

library(purrr)
map2(bioactives, genes, ~ model_function_covariates_for_table(.x, .y))

-output

$leptin

Call:
lm(formula = M1, data = df)

Coefficients:
(Intercept)        gene1          age          sex  
   0.692454    -0.200365    -0.001285     0.044467  


$insulin

Call:
lm(formula = M1, data = df)

Coefficients:
(Intercept)        gene2          age          sex  
  0.7475482   -0.1388409   -0.0006337   -0.1919895  

The tab_model will be applied on each of those elements

out <- map2(bioactives, genes, ~ 
         model_function_covariates_for_table(.x, .y) %>% 
          tab_model)

out[[1]]

enter image description here

out[[2]]

enter image description here


In base R, the corresponding function is Map

Map(model_function_covariates_for_table, bioactives, genes)
Related