Is there a way to pull labels from a separate table in tbl_summary?

Viewed 332

I am using tbl_summary from the gtsummary package to create publication tables summarizing long lists of categorical data from a data table. For publication purposes, tbl_summary allows assigning human readable variable labels instead of variable names using the argument

label = grade ~ "Tumor Grade"

and for multiple variables in the form of a list:

label = list(api00 ~ "API in 2000",
             api99 ~ "API in 1999",
             api98 ~ "API in 1998")

However, I have hundreds of variables and the variable names with the corresponding human readable lables are stored in another table altogether.

How can I create a list of the format above (ie. var_name ~ "Variable label") from a separate table with those values and pass it into tbl_summary label as argument?

In other words, I have a table of the format:

VAR_NAME   VAR_LABEL
var1       First variable
var2       Second variable
...        ...
var159     Hundred fifty ninth variable

Is there a way to read this table and pass the arguments to the label function of tbl_summary as a list:

label = list(VAR_NAME ~ "VAR_LABEL")

Thanks in advance.

2 Answers

I think you're best bet will be to save the variable labels as a named list. They are a bit easier to work with, and you can pass the named list to any label argument in gtsummary.

library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.3.6'

list_of_labels <-
  list(age = "Patient Age, yrs",
       grade = "Path. Tumor Grade")

tbl <-
  trial %>%
  select(age, grade) %>%
  tbl_summary(label = list_of_labels)

# convert a data frame into a list
data.frame(variable = c("age", "grade"),
           label = c("Patient Age, yrs", "Path. Tumor Grade")) %>%
  tibble::deframe() %>%
  as.list()
#> $age
#> [1] "Patient Age, yrs"
#> 
#> $grade
#> [1] "Path. Tumor Grade"

enter image description here

Created on 2021-02-20 by the reprex package (v1.0.0)

You can create the labels dynamically using Map. If your dataframe is called df, try :

formula_list <- Map(function(x, y) as.formula(sprintf('%s~"%s"', x, y)), 
                    df$VAR_NAME, df$VAR_LABEL)

Then use this formula_list in label.

label = formula_list
Related