Search code examples
rgt

Hide grand summary rows labels in gt package


Problem:

I am using the gt package to create a table and I can't figure out how to hide the column generated by the labels of the grand summary rows (and I´m not able to generate the grand summary rows without the labels either).

cols_hide() doesn´t seem to work with this column.

https://i.sstatic.net/iwYjQ.jpg

Any help is very much appreciated =)

Reproducible example (omitted formatting):

# Load libraries
library(dplyr)
library(gt)

# Create dataset and group by "Cat"
x3 <- structure(list(year = c(2012, 2012, 2013, 2013, 2014, 2014), 
                     Cat = c(1, 0, 1, 0, 1, 0), 
                     Num = c(124, 3774, 143, 3913, 150, 4122),
                     Fem = c(83, 2467, 99, 2560, 111, 2702), 
                     Male = c(41, 1307, 44, 1353, 39, 1420), 
                     P.Fem = c(0.67, 0.65, 0.69, 0.65, 0.74, 0.66)), 
      row.names = c(NA, -6L),
      class = c("tbl_df", "tbl", "data.frame")) %>%
   group_by(Cat)

# Create table using gt
t_RES <- gt(x3,groupname_col = "year") %>%
  
  tab_header(title = "Title",
             subtitle = "2012-2014") %>%
  
  tab_spanner(label = "Gen",
              columns = c("Fem","Male","P.Fem")) %>%
  
  grand_summary_rows(fns = list(
    "Eg1" = ~ sum(.),
    "Eg2" = ~ mean(.)),
    formatter = fmt_number,
    decimals = 0,
    use_seps = FALSE) %>%
  
  cols_hide(columns = c(1,2)) %>%
  
  tab_style(style = cell_text(align = "center"),
            locations = cells_row_groups()) %>%

  print()

Solution

  • You can set the stub.border.width to zero within tab_options()

    # Load libraries
    library(gt)
    library(tidyverse)
    # Create dataset and group by "Cat"
    x3 <- structure(list(year = c(2012, 2012, 2013, 2013, 2014, 2014), 
                         Cat = c(1, 0, 1, 0, 1, 0), 
                         Num = c(124, 3774, 143, 3913, 150, 4122),
                         Fem = c(83, 2467, 99, 2560, 111, 2702), 
                         Male = c(41, 1307, 44, 1353, 39, 1420), 
                         P.Fem = c(0.67, 0.65, 0.69, 0.65, 0.74, 0.66)), 
                    row.names = c(NA, -6L),
                    class = c("tbl_df", "tbl", "data.frame")) %>%
      group_by(Cat)
    
    # Create table using gt
    gt(x3,groupname_col = "year") %>%
      
      tab_header(title = "Title",
                 subtitle = "2012-2014") %>%
      
      tab_spanner(label = "Gen",
                  columns = c("Fem","Male","P.Fem")) %>%
      
      grand_summary_rows(
        columns = c("Fem","Male","P.Fem"),
        fns = list(
        "Eg1" = ~ sum(.),
        "Eg2" = ~ mean(.)),
        formatter = fmt_number,
        decimals = 0,
        use_seps = FALSE) %>%
      
      cols_hide(columns = c(1,2)) %>%
      
      tab_style(style = cell_text(align = "center"),
                locations = cells_row_groups()) %>% 
      tab_options(stub.border.width = 0)
    

    Sample