如何将总计添加到 DT::datatable?

2023-12-30

我正在尝试将总计添加到数据表页脚。使用来自不同来源的代码,我使用 Shiny 编写了以下应用程序。问题是,当我运行它时,出现以下消息:

“加工 ...”

并永远留在那里。

我的猜测是 JS() 代码,但无法调试它。

library(shiny)
library(DT)
library(htmltools)

ui <- fluidPage(


  fluidRow(
    column(9, DT::dataTableOutput('withtotal'))
  )

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

  # server-side processing
  mtcars2 = mtcars[, 1:8]
  #sketch <- htmltools::withTags(table(tableHeader(mtcars2), tableFooter(mtcars2)))

  sketch = htmltools::withTags(table(tableFooter(c("",0,0,0,0,0,0,0))))

 opts <- list( footerCallback = JS("function ( row, data, start, end, display ) {",
     "var api = this.api();",
     "var intVal = function ( i ) {",
      "return typeof i === 'string' ?",
       "i.replace(/[\\$,]/g, '')*1 :",
         "typeof i === 'number' ?",
         "i : 0;",
     "};",
     "if (api.column(COLNUMBER).data().length){",
       "var total = api",
       ".column( COLNUMBER )",
       ".data()",
       ".reduce( function (a, b) {",
         "return intVal(a) + intVal(b);",
       "} ) }",
     "else{ total = 0};",
     "if (api.column(COLNUMBER).data().length){",
       "var pageTotal = api",
       ".column( COLNUMBER, { page: 'current'} )",
       ".data()",
       ".reduce( function (a, b) {",
        " return intVal(a) + intVal(b);",
       "} ) }",
    "else{ pageTotal = 0};",
     "$( api.column(COLNUMBER).footer() ).html(",
       "'$'+pageTotal",
     ");",
   "}"))


  output$withtotal = DT::renderDataTable(DT::datatable(mtcars2,container = sketch, options = opts))      


}

options(shiny.error = browser)
# Run the application 
shinyApp(ui = ui, server = server)

这是一个没有使用Shiny的版本。我使用了与上面 @gscott 相同的 JavaScript,但这是针对独立表的。我在 RMarkdown 文档中使用了它。我一直在努力解决这个问题的关键是container参数,它将页脚添加到表中。

library(htmlwidgets)
library(DT)
library(htmltools)

sketch <- htmltools::withTags(table(
  tableHeader(colnames(mtcars)), 
  tableFooter(c(0,0,0,0,0,0,0,0,0,0,0,0))
))

jsCode <- "function(row, data, start, end, display) {
  var api = this.api(), data;
  total = api.column(7, {page: 'current'}).data().reduce( function(a, b) { return a + 
b}, 0);
  total2 = api.column(6, {page: 'current'}).data().reduce( function(a, b) { return a 
+ b}, 0);
  total3 = api.column(2, {page: 'current'}).data().reduce( function(a, b) { return a 
+ b}, 0);
  $( api.column(7).footer() ).html('Total: ' + total.toFixed(2));
  $( api.column(6).footer() ).html('Total: ' + total2.toFixed(2));
  $( api.column(2).footer() ).html('Total: ' + total3.toFixed(2))
  }"

DT::datatable(mtcars, container = sketch, options=list(scrollY=300, scrollX=TRUE, scroller=TRUE, footerCallback = JS(jsCode)))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将总计添加到 DT::datatable? 的相关文章

随机推荐