清除此问题后提出了此问题:将长 gtsummary() 表拆分为 n 个较小的表
本质上,已解决的问题适用于示例数据库。将其应用于我自己的数据框后,Error: Can't coerce element 1 from a double to a integer when try to split gtsummary table
发生了。我尝试了一些事情,比如清理班级、删除属性等......但没有成功:这是我的代码:
library(gt)
library(gtsummary)
library(tidyverse)
# split function by Daniel D. Sjoberg
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
}
)
}
# my dataframe and applied split function
df <- structure(list(A = c(17729L, 17131L, 20617L, 18028L, 19721L,
20418L, 17828L, 21115L, 17928L, 19721L, 17131L, 19522L, 17131L,
19920L, 19123L, 16036L, 18028L, 17231L, 22012L, 14840L, 24502L,
19024L, 17729L, 19721L, 20318L, 21215L, 20020L, 18625L, 18824L,
17131L, 19920L, 16733L, 15737L, 19522L, 18426L, 16832L), B = c(14037L,
12886L, 11150L, 13571L, 15435L, 14298L, 15188L, 17953L, 15198L,
13135L, 14899L, 12061L, 11087L, 12825L, 14142L, 15426L, 14960L,
13814L, 4434L, 6678L, 23550L, 9417L, 13988L, 13734L, 14087L,
17524L, 16874L, 13605L, 15501L, 13814L, 12164L, 8219L, 12588L,
14633L, 15746L, 10999L), C = c(1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L,
2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 1L), D = c(43L, 34L,
43L, 52L, 62L, 50L, 49L, 65L, 46L, 63L, 47L, 58L, 61L, 51L, 62L,
55L, 57L, 71L, 50L, 34L, 42L, 58L, 43L, 64L, 40L, 58L, 49L, 64L,
67L, 63L, 48L, 22L, 74L, 64L, 53L, 56L)), row.names = c(NA, -36L
), class = "data.frame")
table1 <- tbl_summary(df)
table1
split_gtsummary_tbl(table1, .split_after = c("marker", "B"))