簡體   English   中英

更改 shiny 數據表的列總和 output

[英]Change column sum output of shiny datatable

這是這個問題的后續問題: Adding Total/Subtotal to the bottom of a DataTable in Shiny使用以下代碼片段:

library(shiny)
library(DT)

ui <- shinyUI(fluidPage(
  h1('Testing TableTools'),
  mainPanel(
    dataTableOutput('display')
  )      
))

Names <- c("",names(mtcars))
FooterNames <- c(rep("",4),Names[5:6],rep("",6))

server <- function(input, output, session) {

  sketch <- htmltools::withTags(table(
    tableHeader(Names),tableFooter(FooterNames)
  ))

  opts <- list(
    dom = 'Bfrtip', buttons = list('colvis','print',list(extend='collection',text='Download',buttons = list('copy','csv','excel','pdf'))),
               footerCallback = JS(
                 "function( tfoot, data, start, end, display ) {",
                 "var api = this.api(), data;",
                 "$( api.column(5).footer()).html('SubTotal:  '+",
                 "api.column(5).data().reduce( function ( a, b ) {",
                 "return a + b;",
                 "} )",
                 ");",
                 "$( api.column(4).footer()).html('SubTotal: '+",
                 "api.column(4).data().reduce( function ( a, b ) {",
                 "return a + b;",
                 "} )",
                 ");","}")
  )

  output$display <- DT::renderDataTable(container = sketch,extensions = 'Buttons',options = opts,{
    mtcars
  })
}

shinyApp(ui = ui, server = server)

在我的 dataframe 中,我有包含雙精度數的列,逗號后有兩位數字。 小計顯示如下:

1234,51999999999 而不是 1234,52。

我必須在 Javascript 代碼中更改什么才能在逗號后僅獲得兩位數,千位分隔符作為點,小數點作為逗號,以及總和旁邊的歐元 (€) 符號?

如果您使用的是 shiny,為什么要在 JavaScript 中執行此操作? 這是 R 方式:

paste0(
  formatC(1234.51999999999, format="f", big.mark=".",
  decimal.mark = ",", digits=2), "€"
)
# [1] "1.234,52€"

或者使用 JS 來完成這項工作:

library(shiny)
library(DT)

ui <- shinyUI(fluidPage(
  h1("Testing TableTools"),
  mainPanel(
    dataTableOutput("display")
  )
))

Names <- c("", names(mtcars))
FooterNames <- c(rep("", 4), Names[5:6], rep("", 6))

server <- function(input, output, session) {
  sketch <- htmltools::withTags(table(
    tableHeader(Names), tableFooter(FooterNames)
  ))

  opts <- list(
    dom = "Bfrtip", buttons = list("colvis", "print", list(extend = "collection", text = "Download", buttons = list("copy", "csv", "excel", "pdf"))),
    footerCallback = JS(
      "
      function(tfoot, data, start, end, display) {
    var api = this.api(),
        data;
    var sum1 =  api.column(5).data().reduce(function(a, b) {
        return a + b;
    });
    sum1 = Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(sum1)

    $(api.column(5).footer()).html('SubTotal:  ' + sum1)
}
"
    )
  )

  output$display <- DT::renderDataTable(container = sketch, extensions = "Buttons", options = opts, {
    mtcars
  })
}

shinyApp(ui = ui, server = server)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM