Search code examples
rlogistic-regressiongtsummarybroom

Wald CI tibble for tbl_regression doesn't exponentiate values


This thing has been driving me crazy. The example below is from documentation: https://www.danieldsjoberg.com/gtsummary/articles/gallery.html#wald-ci

Basically, I'm running a logistic regression and trying to use tbl_regression to give me a publish-ready tables. By default, tbl_regression publishes Wald p-values but profile-likelihood confidence intervals. Per documentation, I can force it to use a Wald CI by using a tibble.

My problem is that the code below exponentiates the ORs but NOT the confidence interval. I've tried changing the "exponentiate = FALSE" to "exponentiate = TRUE" in the my_tidy function and it makes no difference. How do I fix this?

my_model <- glm(outcome ~ var1 + var2 + var3 + var4, family = binomial (link = logit), data=df)

my_tidy <- function(x, exponentiate = FALSE, conf.level = 0.95, ...) {
  dplyr::bind_cols(
    broom::tidy(x, exponentiate = exponentiate, conf.int = FALSE),
    # calculate the confidence intervals, and save them in a tibble
    confint.default(x) |> 
      dplyr::as_tibble() |> 
      rlang::set_names(c("conf.low", "conf.high"))
  )
}

tbl_regression(my_model, tidy_fun = my_tidy, exponentiate = TRUE)


Solution

  • You just need to exponentiate the confidence interval of the odds ratio as well. The confidence interval is constructed with confint.default() but nothing in your code is exponentiating it. So just apply exp() to confint.default(), but only if exponentiate = TRUE. Note that I've included conditional evaluation in the pipe which is not supported by the base R pipe |>, but is supported by the magrittr pipe %>%.

    my_tidy <- function(x, exponentiate = FALSE, conf.level = 0.95, ...) {
      dplyr::bind_cols(
        broom::tidy(x, exponentiate = exponentiate, conf.int = FALSE),
        # calculate the confidence intervals, and save them in a tibble
        confint.default(x) %>%
        { if (exponentiate) exp(.) else . } %>%
          dplyr::as_tibble() %>% 
          rlang::set_names(c("conf.low", "conf.high"))
      )
    }