gt
gt copied to clipboard
add a `.fn` parameter to `cols_label()`
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 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:

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_"))
Fixed by #1158.