简体   繁体   English

闪亮和R中的DT:自定义数字格式

[英]DT in Shiny and R: Custom number formatting

I have a shiny-app that displays a datatable using the DT -package. 我有一个使用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). 例如,我想要一个货币值显示如下:1,234.50€而不是DT -way,它显示它像$ 1,234.5(注意符号的变化,货币符号的位置以及后面的数字)小数点)。

An MWE looks like this: MWE看起来像这样:

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. 当插入另一个字符如“E”时,字符仍然显示在开头而不是结尾。 Furthermore, the numeric value does not get a "big-mark". 此外,数值不会得到“大标记”。

Any ideas? 有任何想法吗?

You can change the position of the currency symbol in the .js file from the datatable package. 您可以从datatable包更改.js文件中的货币符号的位置。

Edit the line of the DTWidget.formatCurrency function 编辑DTWidget.formatCurrency函数的行

 $(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. 在R库中的DT / htmlwidgets / datatables.js文件中。

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? 对我有用,那就是你尝试过的,你没有看到任何符号?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM