LBZR
LBZR

Reputation: 181

Formatting a R data table (DT) column into currency as well as millions/thousands

I am using the DT package's render functions to display a data table. I want to show some columns as dollar amounts, but also in millions. Using the code given below, I am able to transform intended column 3 to 5 into dollar amount currency.

Is there a way to also add another formatting such that we see the value as e.g. $1.01 M instead of $1,012,310.23 ?

output$my.summary<-DT::renderDataTable({
    DT::datatable(my.summary()) %>% 
        formatCurrency(c(3:5),digits=2)
  })

my.summary is just a datatable from a reactive component, and I want to reuse objects as much as possible rather than modifying anything in source (e.g., divide by 1e-06 and adding M in end)

A simple solution that I can use in above block is highly appreciated! Thank you!

Upvotes: 2

Views: 1722

Answers (1)

Thomas
Thomas

Reputation: 1302

This question has been answered already: Format number into K(thousand), M(million) in Shiny DataTables

Thus, use:

formatThousands <- JS(
  "function(data) {",
  "return '$' + (data / 1000).toFixed(1) + 'K'",
  "}")

mtcars %>% 
  datatable(options = list(
    columnDefs = list(list(
      targets = c(3), render = formatThousands
    ))
  ))

Or without JavaScript you could try this:

mtcars %>% 
  mutate(disp = disp/1000) %>% 
  DT::datatable() %>% 
  DT::formatString(c(3), prefix = "$", suffix = "K")

You are not editing anything by reference, the original data set remains the same through the magrittr pipe operator

Upvotes: 6

Related Questions