How To Add totals to a DT::datatable?

前端 未结 3 1458
夕颜
夕颜 2021-01-05 11:06

I am trying to add totals to a data table footer. Using code from different sources, I wrote the following application using Shiny. The problem is, when I run it, the follow

3条回答
  •  时光取名叫无心
    2021-01-05 11:50

    I managed to solve the same problem with the answers above, and the following is my implementation to reduce the amount of repeated JavaScript codes.

    I looped through the columns using columns().eq(0).each(), then aggregate the data, and add the result to the footer.

    library(shiny)
    library(DT)
    
    ui <- fluidPage(
            title = 'Select Table Rows', hr(), h1('A Server-side Table'),
            fluidRow(
                    column(9, DT::dataTableOutput('x3'))
            )
    )
    
    server <- function(input, output, session) {
            mtcars2 = mtcars[, 1:8]
            sketch <- htmltools::withTags(table(
                    class = "display", style = "bootstrap",
                    tableHeader(colnames(mtcars2)),
                    tableFooter(colnames(mtcars2))
            ))
    
            output$x3 = DT::renderDataTable(DT::datatable(mtcars2,
                    container = sketch,
                    extensions = 'Buttons',
                    options = list(
                            scrollX = TRUE, scrollY = TRUE,
                            pageLength = 10, order = list(list(1, 'asc')),
                            dom = 'Blrtip', buttons = c('copy', 'csv', 'excel', 'pdf', 'print'),
                            footerCallback = JS(
                                    "function( tfoot, data, start, end, display ) {",
                                            "var api = this.api(), data;",
                                            "api.columns().eq(0).each( function(index) {",
                                                    "var col = api.column(index);",
                                                    "if(index == 0) return $(api.column(index).footer()).html('Total')",
                                                    "var data = col.data();",
                                                    "total = data.reduce( function(a, b) { return a + b }, 0 );",
                                                    "$( api.column(index).footer() ).html(total.toFixed(2));",
                                            "})",
                                  "}"
                          ))
            ))
    }
    

提交回复
热议问题