gt icon indicating copy to clipboard operation
gt copied to clipboard

add a `.fn` parameter to `cols_label()`

Open mgacc0 opened this issue 2 years ago • 2 comments

Would you consider of interest adding a .fn parameter to cols_label? Someting analogous to dplyr::rename_with.

So we could, for example, remove a prefix with

cols_label(.fn = ~ str_remove(., "^prefix"))

mgacc0 avatar Jul 23 '21 18:07 mgacc0

@mgacc0 you can dynamically set column names by using the .list = argument in col_labels(). For example, consider the country data set. The majority of variables have a prefix of country_, we can apply a series of transformations outside of the table build and supply a new list with names being the existing names and the contents being the new names

library("gt")

# Obtain column names
col_names = colnames(countrypops)
col_names
#> [1] "country_name"   "country_code_2" "country_code_3" "year"          
#> [5] "population"

# Remove the country_ prefix
new_col_names = gsub("country_", "", col_names)
new_col_names
#> [1] "name"       "code_2"     "code_3"     "year"       "population"

# Set the new column names as the list content and, then, set the element
# names to the existing variable names
list_for_dynamic_cols_label = structure(as.list(new_col_names), names=col_names)
list_for_dynamic_cols_label
#> $country_name
#> [1] "name"
#> 
#> $country_code_2
#> [1] "code_2"
#> 
#> $country_code_3
#> [1] "code_3"
#> 
#> $year
#> [1] "year"
#> 
#> $population
#> [1] "population"

# Construct a gt table
countrypops %>%
  dplyr::filter(country_name == "Mongolia") %>%
  tail(5) %>%
  gt() %>%
  cols_label(
   .list = list_for_dynamic_cols_label # pass a list instead of manually specifying
  ) 

Would give:

gt-dynamic-rename-columns-with-cols-label

coatless avatar Aug 09 '21 02:08 coatless

Thanks @coatless. You are telling me that I could write

countrypops %>%
  filter(country_name == "Mongolia") %>%
  slice_tail(n = 5) %>%
  gt() %>%
  cols_label(.list = structure(as.list(str_remove(
    colnames(.), "country_"
  )),
  names = colnames(.)))

I know. I'm suggesting this feature so we could write

countrypops %>%
  filter(country_name == "Mongolia") %>%
  slice_tail(n = 5) %>%
  gt() %>%
  cols_label(.fn = ~ str_remove(., "country_"))

mgacc0 avatar Aug 09 '21 06:08 mgacc0

Fixed by #1158.

rich-iannone avatar Dec 05 '22 22:12 rich-iannone