Search code examples
rgt

cols_label in gt table inside function


is there a solution to have column names in cols_label as strings?

Like

fun <- function( df,column, label )
{
  df %>%
    gt() %>%
    cols_label( column = label)
  
}


fun( mtcars,"cyl", "cylinder")

Solution

  • Use the curly-curly operator.

    library(gt)
    
    fun <- function(df, column, label)
    {
      df %>%
        gt() %>%
        cols_label({{column}} := label)
    }
    
    fun(mtcars, "cyl", "cylinder")
    

    Alternatively, you can use the .list parameter. This will handle vectors of columns.

    library(gt)
    
    fun <- function(df, column, label)
    {
      cols_list = as.list(label) %>% purrr::set_names(column)
      
      df %>%
        gt() %>%
        cols_label(.list = cols_list)
    }
    
    fun(mtcars, "cyl", "cylinder")
    fun(mtcars, c("cyl", "hp"), c("cylinder", "horsepower"))