svenhalvorson
svenhalvorson

Reputation: 1080

Formatting gtsummary tables with checkbox questions

I have been enjoying the gtsummary library quite a bit but I can't find a clean way to display checkbox style questions (select all that apply) gtsummary::tbl_summary. Here is an example:

example_df = tibble::tibble(
  CHOICE1 = sample(c(1, NA), size = 10, replace = TRUE),
  CHOICE2 = sample(c(1, NA), size = 10, replace = TRUE),
  CHOICE3 = sample(c(1, NA), size = 10, replace = TRUE)
)

for(i in 1:3){
  expss::val_lab(example_df[[i]]) = set_names(1, letters[i])
  expss::var_lab(example_df[[i]]) = 'Question 1'
}

example_df %>% 
  gtsummary::tbl_summary(
    type = list(
      CHOICE1 ~ "categorical",
      CHOICE2 ~ "categorical",
      CHOICE3 ~ "categorical"
    )
  )

Ideally, we would just have one header that says 'Question 1' and then each of the columns would be summarized below it. Any suggestions on how to do this properly or gerry rig it?

Thank you!

Upvotes: 2

Views: 355

Answers (1)

Daniel D. Sjoberg
Daniel D. Sjoberg

Reputation: 11764

Great question. Below is an, admittedly, not great solution to your question. But it does get the job done. If you file an GH issue on the gtsummary page, requesting better support for these types of data, we can work together a more concise solution. Happy Programming!

library(gtsummary)
library(tidyverse)

example_df = tibble::tibble(
  CHOICE1 = sample(c(1, NA), size = 10, replace = TRUE),
  CHOICE2 = sample(c(1, NA), size = 10, replace = TRUE),
  CHOICE3 = sample(c(1, NA), size = 10, replace = TRUE)
)

for(i in 1:3){
  expss::val_lab(example_df[[i]]) = setNames(1, letters[i])
  expss::var_lab(example_df[[i]]) = 'Question 1'
}

example_df %>% 
  mutate(across(everything(), ~replace_na(., 0L))) %>%
  gtsummary::tbl_summary(
    type = list(
      CHOICE1 ~ "categorical",
      CHOICE2 ~ "categorical",
      CHOICE3 ~ "categorical"
    )
  ) %>%
  remove_row_type(variables = c(CHOICE2, CHOICE3), type = "header") %>%
  modify_table_body(
    ~.x %>%
      filter(label != "0")
  ) %>%
  as_kable() # converting to kable to display on SO
Characteristic N = 10
Question 1
a 4 (40%)
b 3 (30%)
c 4 (40%)

Created on 2022-01-12 by the reprex package (v2.0.1)

Upvotes: 2

Related Questions