Search code examples
rlabelgtsummary

gtsummary flexible label list for model covariates


I have regression models with slightly different model variables that I merge together in one table. I would like to identify a list of the variable labels to use for all regressions. I use the label argument in the tbl_regression function which calls a list of labels I identified previously.

However, when calling labels for different models, I receive an error message whenever the list includes labels for variables not included in the model. So I can't use one list since each model is different. An error message is shown.

I don't want to identify the labels in the data frame I am using, because I am reducing binary variables to single rows and I would like to identify the variables' levels in the labels as well.

Here is a simplified example with one model:

label_list = list(trt ~ 'Treatment: Drug B vs. A', grade2 ~ 'Grade: III vs. I/II', response ~ 'Response')

tbl_regression_ex1 <-
    coxph(Surv(ttdeath, death) ~ trt + grade2, trial) %>%
    tbl_regression(exponentiate = T, show_single_row = c(trt, grade2), label = label_list)
tbl_regression_ex1

And the error message:

Error:
! Error in `labels=` argument input. Select from ‘trt’, ‘grade2’

Thanks in forward


Solution

  • There are two changes here:

    1. Use a named list instead of a list of formulas. The list of formulas is evaluated in a tidyselect env, and will error if the columns do not exist.
    2. In the show single row argument, you need to use any_of() to reference variables that may not exist in the data set.

    Example below!

    library(gtsummary)
    
    label_list = list(trt = 'Treatment: Drug B vs. A', response = 'Response', grade2 = "Does not exist")
    
    survival::coxph(survival::Surv(ttdeath, death) ~ trt + response, trial) %>%
      tbl_regression(
        exponentiate = T, 
        show_single_row = any_of(c("trt", "grade2")),
        label = label_list
      ) |> 
      as_kable() # convert to kable so table displays on stackoverflow
    #> ✖ `grade2` terms have not been found in `x`.
    
    Characteristic HR 95% CI p-value
    Treatment: Drug B vs. A 1.44 0.98, 2.10 0.064
    Response 0.47 0.30, 0.75 0.001

    Created on 2023-04-22 with reprex v2.0.2