Search code examples
rformattinggt

How can I "wrap" the rows of a single gt table in R, giving the appearance of two side-by-side tables?


I want to take a 20 row x 6 column gt table and orient it such that the last ten rows wrap vertically to the right of the first ten. The end product would be a finalized table that has the appearance of two 10x6 tables arranged side-by-side. The output would have a single title, subtitle, source caption, etc.

See below for the 20x6 table I am starting with.

iris %>% arrange(desc(Sepal.Length)) %>% slice(1:20,) %>% gt() %>%
  tab_header(title = "Title")

I reviewed tab_options in the gt package as well as documentation for the gtExtras package to familiarize myself with different formatting capabilities. Could not find a way to accomplish the stated aim. Still relatively new to R so perhaps I'm missing a simple solution. I could of course produce the two tables separately but looking for the most economical solution. Thanks!


Solution

  • One option would be to reshape your data table before passing it to gt() using e.g. tidyr::pivot_wider and some intermediate steps to create unique identifiers for the rows and the sub"table"s:

    library(gt)
    
    iris %>%
      arrange(desc(Sepal.Length)) %>%
      slice(1:20, ) %>%
      mutate(row = (row_number() - 1) %% 10) |>
      mutate(id = row_number(), .by = row) |> 
      pivot_wider(
        names_from = id, values_from = -c(id, row),
        names_vary = "slowest"
      ) |> 
      select(-row) |> 
      gt() %>%
      tab_header(title = "Title") |> 
      cols_label_with(fn = ~gsub("_\\d+$", "", .x))
    

    enter image description here