Is there a way to add percentage to tbl_regression add_nevent?

Viewed 95

I've just discovered that add_nevent in gtsummary can have the option location = "level". I am rapt! But I would like it to have a percentage as well. I've tried adding statistic = "{n}({p}%)" but nothing changes.

Here is my code:

tbl_regression(glm(rellife ~ age + gender, data = df, family = "binomial"), exponentiate = TRUE) %>% 
  add_nevent(location = "level", statistic = "{n}/{N}%") %>%    # add number of events of the outcome
  add_n(location = "level")

And the table: enter image description here

I would like to have 1601 (93.6%) in the column Event N for Age and so on.

Any help would be appreciated. Thanks

1 Answers

After adding the N and N event, you can use the modify_table_body() function to calculate the event rate. Example below!

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

tbl <-
  glm(response ~ age + grade, trial, family = binomial) %>%
  tbl_regression(exponentiate = TRUE) %>%
  add_nevent(location = "level") %>%
  add_n(location = "level") %>%
  # adding event rate
  modify_table_body(
    ~ .x %>% 
      dplyr::mutate(
        stat_nevent_rate = 
          ifelse(
            !is.na(stat_nevent),
            paste0(style_sigfig(stat_nevent / stat_n, scale = 100), "%"),
            NA
          ), 
        .after = stat_nevent
      )
  ) %>%
  # merge the colums into a single column
  modify_cols_merge(
    pattern = "{stat_nevent} / {stat_n} ({stat_nevent_rate})",
    rows = !is.na(stat_nevent)
  ) %>%
  # update header to event rate
  modify_header(stat_nevent = "**Event Rate**")

enter image description here Created on 2022-03-21 by the reprex package (v2.0.1)

Related