0

How to add total row in DT in Shiny app like in example

enter image description here

I exlplored some topic here, but how to add total in Mean_price column, it's calculate total Turnover / total Qty

How to add total if column quantity in DT dynamicaly changed?

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419

1 Answers1

1

Welcome to SO!

Here is a solution using library(data.table):

library(data.table)
library(DT)

ui <- basicPage(
  h2("Grand total"),
  DT::dataTableOutput("mytable")
)

server <- function(input, output) {

  DT <- data.table (Product = paste("Item", seq(10)), Turnover = round(runif(10, 1000, 3000)), Qty=round(runif(10, 100, 120)), Mean_price=round(runif(10, 10, 30), digits = 2))
  totalDT <- as.data.table(c(Product = "Total", DT[, lapply(.SD, sum, na.rm=TRUE), .SDcols=c("Turnover", "Qty")]))
  totalDT[, "Mean_price" := round(Turnover/Qty, digits = 2)]

  myContainer = htmltools::withTags(table(
    tableHeader(DT),
    tableFooter(as.character(totalDT))
  ))

  output$mytable = DT::renderDataTable({
    DT::datatable(DT, options = list(pageLength = nrow(DT)), rownames = FALSE, container = myContainer)
  })
}

shinyApp(ui, server)

See this for row specific styling.

Edit, after further specification of the desired output (footer): you don't need a callback-function to create a footer, please see this.

ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
  • Sorry, I mean how use js to make grand total line below the DT like this topic https://stackoverflow.com/questions/49135787/total-of-a-column-in-dt-datatables-in-shiny – Andrey Kirson Nov 19 '18 at 21:26