使用复选框问题格式化 gtsummary 表

Formatting gtsummary tables with checkbox questions

我很喜欢 gtsummary 库,但我找不到一种干净的方式来显示复选框样式的问题(select 所有适用的问题)gtsummary::tbl_summary。这是一个例子:

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"
    )
  )

理想情况下,我们只有一个 header 表示 'Question 1',然后每一列都将在其下方进行汇总。关于如何正确执行此操作或对它进行 gerry rig 有任何建议吗?

谢谢!

好问题。诚然,以下是您问题的一个很好的解决方案。但它确实完成了工作。如果您在 gtsummary 页面上提交 GH 问题,请求更好地支持这些类型的数据,我们可以一起制定更简洁的解决方案。编程愉快!

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%)

reprex package (v2.0.1)

创建于 2022-01-12