1

I would like to create the table shown here with gtsummary, can you please let me know?

table

1 Answer 1

3

You can add the odds ratio via a custom function passed to add_difference(). Instructions on how to construct a custom function are here https://www.danieldsjoberg.com/gtsummary/reference/tests.html#custom-functions-1.

I've written an example below. But please take careful note of how fisher.test() constructs the odds ratio from the 2x2 table. You may need to switch the order of the variables in table() or even reverse the order of your variable levels to get the odds ratio you need.

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

# function to calculate OR from 2x2 table
or_fun <- function(data, variable, by, ...) {
  table(data[[by]], data[[variable]]) %>%
    fisher.test() %>%
    broom::tidy()
}
# testing function
or_fun(trial, "trt", "response")
#> # A tibble: 1 × 6
#>   estimate p.value conf.low conf.high method                         alternative
#>      <dbl>   <dbl>    <dbl>     <dbl> <chr>                          <chr>      
#> 1     1.21   0.540    0.633      2.34 Fisher's Exact Test for Count… two.sided

# add OR to a `tbl_summary()`
tbl <-
  trial %>%
  select(response, trt) %>%
  tbl_summary(by = trt, missing = "no", statistic = all_categorical() ~ "{n} / {N} ({p}%)") %>%
  add_difference(test = response ~ or_fun, estimate_fun = response ~ style_ratio) %>%
  modify_header(estimate ~ "**Odds Ratio**")

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

Sign up to request clarification or add additional context in comments.

2 Comments

That's really helpful (as your whole package is!). Is it possible to adapt this code to calculate ORs for more than one characteristic?
Just change add_difference(test = response ~ or_fun) to add_difference(test = everything() ~ or_fun) or list all the variables you want this to apply to instead of everything

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.