Output Column as Currency

Looking to format columns in a data table when output in an R Markdown HTML document.

kableExtra have excellent options in making the table look nicer and formattable has the ability to print text with commas & percentages, but is there package or function that prints a column's text as currency ($)?

EDIT: After reading further the documentation, turns out that formattable does have a function called currency().

I think one option is that maybe you can also reformat your data.frame's columns before printing yourself?
There are several solutions to do that. If it suits you, best one is in :package: scales. Very useful for labelling on graphs. Otherwise, you can build one yourself with sprintf, glue or paste

library(dplyr, warn.conflicts = FALSE)
set.seed(45)
tab <- data_frame(currency = rnorm(10)*5)
                  
tab_currency <- tab %>%
  mutate(
    currency_1 = paste("$", format(round(currency, 2L), nsmall = 2L)),
    currency_2 = sprintf("$ %.2f", currency),
    currency_3 = glue::glue("$ {format(round(currency, 2L), nsmall = 2L)}"),
    currency_4 = scales::dollar(currency),
    currency_5 = scales::dollar_format(negative_parens = TRUE)(currency)
  )
#> Warning: le package 'bindrcpp' a été compilé avec la version R 3.4.4

glimpse(tab_currency)
#> Observations: 10
#> Variables: 6
#> $ currency   <dbl> 1.7039985, -3.5167015, -1.8976887, -3.7302372, -4.4...
#> $ currency_1 <chr> "$  1.70", "$ -3.52", "$ -1.90", "$ -3.73", "$ -4.4...
#> $ currency_2 <chr> "$ 1.70", "$ -3.52", "$ -1.90", "$ -3.73", "$ -4.49...
#> $ currency_3 <chr> "$  1.70", "$ -3.52", "$ -1.90", "$ -3.73", "$ -4.4...
#> $ currency_4 <chr> "$1.70", "$-3.52", "$-1.90", "$-3.73", "$-4.49", "$...
#> $ currency_5 <chr> "$1.70", "($3.52)", "($1.90)", "($3.73)", "($4.49)"...

Then you can print the table using kable

knitr::kable(tab_currency)  
currency currency_1 currency_2 currency_3 currency_4 currency_5
1.7039985 $ 1.70 $ 1.70 $ 1.70 $1.70 $1.70
-3.5167015 $ -3.52 $ -3.52 $ -3.52 $-3.52 ($3.52)
-1.8976887 $ -1.90 $ -1.90 $ -1.90 $-1.90 ($1.90)
-3.7302372 $ -3.73 $ -3.73 $ -3.73 $-3.73 ($3.73)
-4.4905366 $ -4.49 $ -4.49 $ -4.49 $-4.49 ($4.49)
-1.6739705 $ -1.67 $ -1.67 $ -1.67 $-1.67 ($1.67)
-2.5068908 $ -2.51 $ -2.51 $ -2.51 $-2.51 ($2.51)
-0.8726785 $ -0.87 $ -0.87 $ -0.87 $-0.87 ($0.87)
9.0451870 $ 9.05 $ 9.05 $ 9.05 $9.05 $9.05
-1.1505249 $ -1.15 $ -1.15 $ -1.15 $-1.15 ($1.15)

Know that :package: DT for html table have also an option for currency column.
See on first column.

library(DT)
datatable(tab_currency) %>%
  formatCurrency('currency')

Created on 2018-05-03 by the reprex package (v0.2.0).

4 Likes