Search code examples
rfunctiongt

Controlling width of column from gt package with a function


I am having trouble to control the width of my gt tables with this function I created.

Any help?

cols_fn <- function(data, y){
data %>%
    select(1:4) %>%
    gt() %>%
    gt_theme_espn() %>% cols_width(4 ~ paste0(glue::glue({y}),"px"))

}

cols_fn(mtcars,y = 900)

I have this error message: Error in force(..1) : object 'y' not found


Solution

  • One approach to make your function work would be to use as.formula like so:

    library(gt)
    library(gtExtras)
    library(dplyr)
    
    cols_fn <- function(data, y) {
      data %>%
        select(1:4) %>%
        gt() %>%
        gt_theme_espn() %>%
        cols_width(as.formula(glue::glue("4~px({y})")))
    }
    
    cols_fn(head(mtcars), y = 900)
    

    enter image description here