DT in Shiny and R: Custom number formatting

女生的网名这么多〃 提交于 2019-12-09 10:36:10

问题


I have a shiny-app that displays a datatable using the DT-package. What I want is to be able to format columns in a custom way. For example I want a currency value to be displayed like this: 1,234.50€ instead of the DT-way, which displays it like this $1,234.5 (notice the change in the symbol, the position of the currency-symbol as well as the numbers after the decimal-point).

An MWE looks like this:

library(shiny)
library(DT)

shinyApp(
  # UI
  ui = fluidPage(DT::dataTableOutput('tbl')),

  # SERVER
  server = function(input, output) {
    dat <- data.frame(cur = 1234.5, # supposed to be displayed as: 1,234.50€ | Bad! 
                                         # displayed as $1,234.5
                      perc = 0.123456, # 12.34% | Good!
                      num = 1000) # 1,000 | Bad! displayed as 1000

    # render DT
    output$tbl = DT::renderDataTable(
      datatable(dat) %>%
        formatCurrency(c('cur'), "$") %>%
        formatPercentage('perc', 2) %>%
        formatRound('num', digits = 0)
    )
  }
)

It does a fairly good job, however, when changing the currency-symbol to , the symbol disappears. When inserting another character like "E", the character is still displayed at the beginning not at the end. Furthermore, the numeric value does not get a "big-mark".

Any ideas?


回答1:


You can change the position of the currency symbol in the .js file from the datatable package.

Edit the line of the DTWidget.formatCurrency function

 $(thiz.api().cell(row, col).node()).html(currency + markInterval(d, interval, mark));

to simply

 $(thiz.api().cell(row, col).node()).html(markInterval(d, interval, mark) + currency);

in the DT/htmlwidgets/datatables.js file in the directory of your R librarys.

As for the € Symbol,

formatCurrency(c('cur'), currency = "\U20AC", interval = 3, mark = ",", digits = 2)

does work for me, thats what you tried and you don't see any symbol?



来源:https://stackoverflow.com/questions/33171279/dt-in-shiny-and-r-custom-number-formatting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!