I would like to create the table shown here with gtsummary, can you please let me know?
1 Answer
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**")
Created on 2022-05-08 by the reprex package (v2.0.1)
2 Comments
Andrea M
That's really helpful (as your whole package is!). Is it possible to adapt this code to calculate ORs for more than one characteristic?
Daniel D. Sjoberg
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