rgtr-colnames

R gt package - How to rename all columns at once


I have a dataframe like this one:

library(gt)
library(tidyverse)
library(gtExtras)

test = dplyr::tibble(
  id = 1:3,
  type1_value1 = 2:4,
  type1_value2 = 3:5,
  type2_value1 = 4:6,
  type2_value2 = 5:7)

I actually want to have only spanners but no col_lables, which doesnt seem to work, when I try it:

test %>%
  gt() %>%
  tab_spanner(
    label = "span1",
    columns = c(2:3)) %>%
  tab_spanner(
    label = "span2",
    columns = c(4:5)) %>%
  tab_options(column_labels.hidden = TRUE)

The spanners just wont appear. If you know any solution what is wrong, please give me a hint. I tried to work around it now by just renaming every column with no name.

test %>%
  gt() %>%
  tab_spanner(
    label = "span1",
    columns = c(2:3)) %>%
  tab_spanner(
    label = "span2",
    columns = c(4:5)) %>%
  cols_label(id = "", type1_value1 = "", type1_value2 = "", 
             type2_value1 = "", type2_value2 = "") 
  
  cols_label(id = "", type1_value1 = "", type1_value2 = "", 
             type2_value1 = "", type2_value2 = "") 

My real df has over 200 columns. How can I rename them all at once? They should all get the empty name "".

Thanks for any help.


Solution

  • Using the tidyselect helper everything() you could rename all columns at once like so:

    library(gt)
    library(tidyverse)
    
    test %>%
      gt() %>%
      tab_spanner(
        label = "span1",
        columns = c(2:3)
      ) %>%
      tab_spanner(
        label = "span2",
        columns = c(4:5)
      ) %>%
      cols_label(
        everything() ~ ""
      )
    

    enter image description here