【问题标题】:R DataTable: How to format a column to show numbers with comma for thousends?R数据表:如何格式化一列以用逗号显示千位数字?
【发布时间】:2019-01-25 14:44:51
【问题描述】:

在 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'))
                                           ))

更新一:如何申请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'))
                                       ))

我已更改您的答案以匹配我的专栏名称。

【问题讨论】:

  • 没有 Javascript 的选项可能会将列转换为使用 scales::comma() &gt; scales::comma(22381) [1] "22,381" 格式化的字符

标签: r shiny dt


【解决方案1】:

您正在寻找DT::formatCurrency

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

更新1:

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()),然后再将其传递给另一个步骤。

【讨论】:

  • Ty,我试过你的回答,但它给了我一个错误,请参阅我的更新。您能解释一下如何在闪亮的渲染函数中应用formatCurrency 吗?
  • 也许你也可以帮忙回答这个问题:stackoverflow.com/questions/38642515/…
  • 谢谢,它按预期工作。但现在我失去了第二列的降序。我不知道如何 %>% 在选项列表中使用该选项。请您扩展那部分。
猜你喜欢
  • 2015-03-25
  • 2013-11-28
  • 2017-08-23
  • 2022-12-06
  • 2015-04-13
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 2015-06-10
相关资源
最近更新 更多