R DataTable:如何设置列的格式以显示带有逗号的数字以表示数字?

时间:2018-08-19 03:57:45

标签: r shiny dt

在Shiny里面,我正在渲染一个数据表。

我正在阅读DT软件包的选项,并且发现要做到这一点,我需要了解Javascript。

https://rstudio.github.io/DT/options.html

m = as.data.frame(matrix(round(rnorm(100, 1e5, 1e6)), 20))
datatable(m, options = list(
  rowCallback = JS(
    "function(row, data) {",
    "var num = '$' + data[3].toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');",
    "$('td:eq(3)', row).html(num);",
    "}")
), callback = JS("table.order([3, 'asc']).draw();"))

我对JS不太了解,所以我问这个问题。我现在最大的数字是:22381,最低的是0。

我想显示:22381为22,381。如果可能的话:22381,S / .22,381。

这是我的DataTable现在呈现的方式,我正在使用这些选项来对收入进行排序(降序)。

output$products <- renderDataTable(products_ss(),
                                           options = list(
                                             order = list(list(2, 'desc'))
                                           ))

更新1:如何应用formatCurrency

像这样应用它会产生错误:

您已指定列:itemRevenue,但数据的列名称为

output$productos_sams <- renderDataTable(productos_samsung()  %>% 
                                         formatCurrency(c('itemRevenue'), currency = ' S/.',
                                                        interval = 3, mark = ',', before = FALSE),
                                       options = list(
                                         order = list(list(2, 'desc'))
                                       ))

我已更改您的答案以匹配我的列名。

1 个答案:

答案 0 :(得分:5)

您正在寻找DT::formatCurrency

library(DT)
datatable(m) %>% 
             formatCurrency(c('V1', 'V2', 'V3', 'V4', 'V5'), currency = ' S/.',
                            interval = 3, mark = ',', before = FALSE)

Update1:​​

library(shiny)
library(DT)
#Use DT::dataTableOutput and DT::renderDataTable as shiny also has these functions name
shinyApp(
  ui = fluidPage(fluidRow(column(12, DT::dataTableOutput('tbl')))),
  server = function(input, output) {
    m <- reactive({m <- as.data.frame(matrix(round(rnorm(100, 1e5, 1e6)), 20))})
    output$tbl = DT::renderDataTable(
      datatable(m()) %>% formatCurrency(c('V1', 'V2', 'V3', 'V4', 'V5'), currency = ' S/.',
                                           interval = 3, mark = ',', before = FALSE) 
    )
  }
)

https://rstudio.github.io/DT/shiny.html中一样 DT :: renderDT()的第一个参数可以是数据对象,也可以是datatable()返回的表小部件。当您想在以Shiny呈现窗口小部件之前对其进行操作时,后一种形式可能会很有用,例如您可以将格式设置功能应用于表格小部件:。因此,您需要先datatable(m()),然后再进行下一步。