简体   繁体   中英

GrandTotal in DT Shiny with dynamic column quantity

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

在此处输入图片说明

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM