Skip to content

Instantly share code, notes, and snippets.

@isteves
Created July 14, 2020 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isteves/8db7e17e3ff3f69433e58306910ff4a7 to your computer and use it in GitHub Desktop.
Save isteves/8db7e17e3ff3f69433e58306910ff4a7 to your computer and use it in GitHub Desktop.
Flexible way to format table values using dplyr & formattable
library(tidyverse) #need dplyr 1.0.0+ https://www.tidyverse.org/blog/2020/03/dplyr-1-0-0-summarise/
library(formattable)
df <- tibble(spent = 1:10,
refund = 100:109,
perc = seq(0.1, 1, 0.1),
num = 1000:1009,
blah = 1000:1009)
style_table_values <- function(df,
comma = NULL,
percent = NULL,
currency = NULL,
comma_digits = 0,
percent_digits = 1,
currency_digits = 0) {
comma_expr <- enexpr(comma)
percent_expr <- enexpr(percent)
currency_expr <- enexpr(currency)
df %>%
mutate(across(c(!!comma_expr), formattable::comma, digits = comma_digits),
across(c(!!percent_expr), formattable::percent, digits = percent_digits),
across(c(!!currency_expr), formattable::currency, digits = currency_digits))
}
style_table_values(df,
comma = contains("num"),
percent = c(contains("perc"), contains("spent")),
percent_digits = 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment