Home > database >  add labels to gt table with for loop over column names
add labels to gt table with for loop over column names

Time:04-02

I have the following data table .

library(dplyr)
library(gt)

df <- tibble(
      `model 2000` = c("a", "b"), 
      `car 2022` = c("f", "d")
) 

I would like to loop over a vector of column names and perform a string replace, then append this to the gt table

my_cols <- colnames(df)  


for(i in my_cols){
      
            
   df <- df %>%
                    gt() %>%
                    cols_label(
                          
                              i = str_trim(str_remove(i, "2020|2021|2022"))
                
          ) 
 df

}

I want to be able to change the names after the GT table is created using this for loop but when the loop passes the values in my_cols, they aren't recognized... any help?

Here is the error:

Error: All column names provided must exist in the input `.data` table. 

CodePudding user response:

The best way to do this is to eschew looping and pass a named vector and splice it inside cols_labels():

my_cols <- setNames(str_trim(str_remove(names(df), "2020|2021|2022")), names(df))   

df %>%
    gt() %>%
    cols_label(!!!my_cols)

If for some reason you must use a loop, you need to create the gt() object outside of the loop, otherwise after the first iteration you're passing an object that is already class gt_tbl to the gt() function which causes an error. You also need to use the Walrus operator := instead of = and the LHS needs to be a symbol or a glue string.

my_cols <- names(df) 

df <- df %>%
  gt()

for(i in my_cols) {
  df <-  df %>%
    cols_label("{i}" := str_trim(str_remove(i, "2020|2021|2022"))) # or !!sym(i) := ...
}   

df

enter image description here

CodePudding user response:

You can use the .list option in cols_label().


my_cols <- colnames(df)  

df %>%
  gt() %>%
  cols_label(
    .list = setNames(as.list(str_trim(str_remove(my_cols, "2020|2021|2022"))), my_cols)    
  )

However, it seem much easier to just do this:

my_cols <- colnames(df)  

df %>% 
  rename_with(~str_trim(str_remove(.x, "2020|2021|2022")), .cols =my_cols) %>% 
  gt()

Input:

df <- tibble(
  `model 2021` = c("a", "b"), 
  `car 2022` = c("f", "d")
) 
  • Related