I have a table containing multiple statistics per group (in this case: site). I have a couple of sites that have a really long name that forces the first column to expand to contain all the characters. This makes the table larger than necessary.
Hence, for the rows with the ‘row_type` = label I want all the cells in the columns after the label to merged into one cell. I think this will prevent the first column to expand in such way that it has a lot of white space.
Below is an example with a really long name (I left the HTML output out of the results as I am not sure if HTML is supported).
library(tibble)
library(dplyr)
library(gtsummary)
example_data <- tibble(species = c(replicate(10, "species_1"),
replicate(10, "species_2"),
replicate(10, "species_3")),
site_1 = rnorm(30),
site_2_realy_long_name_that_goes_on_and_on = rnorm(30),
site_3 = rnorm(30)) %>%
mutate(species = factor(species, levels = c("species_1", "species_2", "species_3")))
table_1 <- example_data %>%
tbl_summary(
include = starts_with("site"),
by = species, # split table by group
missing = "no", # don't list missing data separately
type = all_continuous() ~ "continuous2",
statistic = list(all_continuous() ~ c("{N_miss}",
"{mean} ({sd})",
"{median} ({p25}, {p75})",
"{min}, {max}")
)
)
table_1$table_body |>
dplyr::filter(row_type == "label")
#> # A tibble: 3 × 8
#> variable var_type var_label row_type label stat_1 stat_2 stat_3
#> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#> 1 site_1 continu… site_1 label site… <NA> <NA> <NA>
#> 2 site_2_realy_long_name… continu… site_2_r… label site… <NA> <NA> <NA>
#> 3 site_3 continu… site_3 label site… <NA> <NA> <NA>
Created on 2024-08-07 with reprex v2.1.1
I have tried to transform the table_1 to a gt object (table_1 |> as_gt()
) and see if I can modify it from there. I have found functions to merge columns, but this will affect all rows. Other questions on stackoverflow deal with merging rows in a single column.
The desired output is a merged label rows with the label column and the stat_xx columns that contains the label.
schonhose is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.