R-newbie
R-newbie

Reputation: 23

How to dynamically add variables to gtsummary::tbl_summary() to calculate statistics for continuous variables

I want to create a function that would automatically generate the tables with summary statistics when i parse different column names. I am trying to create a function for gtsummary I have tried enquo and deparse but both don't seem to help. Can somebody please guide me in what I am doing wrong here.

get_stats <- function (var2) {
var2 <- dplyr::enquo(var2)
grp_val <- deparse(substitute(var2))
 df %>% 
   gtsummary::tbl_summary(.,
      by = trt,
      missing = "no",
      type =
        list(!!var2 ~ "continuous2"),
      statistic = list(
        "{{var2}}" = c(
          "{N_nonmiss}",
          "{mean} ({sd})",
          "{median} ({p25}, {p75})",
          "{min}, {max}"
        )
      )
  ,
      digits = !!var2 ~ c(0, 1, 1, 1)
    )
}

The error I keep getting is Error: Error in type= argument input. Select from ‘age’, ‘trt’.

When I use this with the trial data without parsing anything it works fine.

trial %>% 
  dplyr::select(age, trt) %>% 
    dplyr::mutate_if(is.factor, as.character()) %>%
    gtsummary::tbl_summary(
                           by = trt,
                           missing = "no",
                           type =
                             list(age ~ "continuous2"),
  statistic = list(
    "age" = c(
      "{N_nonmiss}",
      "{mean} ({sd})",
      "{median} ({p25}, {p75})",
      "{min}, {max}"
    ))
    ,
    digits = age ~ c(0, 1, 1, 1)
  )

Expected output from the code

Upvotes: 0

Views: 839

Answers (1)

stefan
stefan

Reputation: 123783

Using rlang::as_name and named lists you could do:

library(gtsummary)

get_stats <- function(df, var2) {
  var2_str <- rlang::as_name(rlang::enquo(var2))
  df %>%
    gtsummary::tbl_summary(.,
      by = trt,
      missing = "no",
      type = setNames(list(c("continuous2")), var2_str),
      statistic = setNames(list(c(
          "{N_nonmiss}",
          "{mean} ({sd})",
          "{median} ({p25}, {p75})",
          "{min}, {max}"
        )), var2_str
      ),
      digits = setNames(list(c(0, 1, 1, 1)), var2_str),
    )
}

trial %>%
  select(age, trt) %>%
  dplyr::mutate_if(is.factor, as.character()) %>%
  get_stats(age)

enter image description here

Upvotes: 1

Related Questions