Created
February 9, 2021 14:48
-
-
Save ddsjoberg/1f400732f0bf9bc9ae6ad1dd8b1cf914 to your computer and use it in GitHub Desktop.
Split a gtsummary table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
split_gtsummary_tbl <- function(x, .split_after) { | |
# get row index where splits occur | |
df_index <- | |
.split_after %>% | |
purrr::map_int(~x$table_body$variable %in% .x %>% | |
which() %>% | |
max()) %>% | |
{union(., nrow(x$table_body))} %>% | |
sort() %>% | |
unique() %>% | |
{tibble::tibble(..index.. = .)} %>% | |
mutate(..group.. = dplyr::row_number()) | |
# nest `x$table_body` within each group | |
nested_table_body <- | |
x$table_body %>% | |
dplyr::mutate(..index.. = dplyr::row_number()) %>% | |
dplyr::left_join(df_index, by = "..index..") %>% | |
tidyr::fill(..group.., .direction = "up") %>% | |
tidyr::nest(data = -..group..) | |
# return gtsummary tbl list | |
purrr::map( | |
seq_len(nrow(nested_table_body)), | |
function(..group..) { | |
x$table_body <- nested_table_body$data[[..group..]] | |
x | |
} | |
) | |
} | |
tt <- | |
trial %>% | |
tbl_summary(by = trt) %>% | |
add_p() | |
split_gtsummary_tbl(tt, .split_after = c("marker", "grade")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment