簡體   English   中英

Shiny DataTable總和一列

[英]Shiny DataTable sum of a column

我有兩個字符列和一個數字列,我正在嘗試計算該數字列的總和。 我嘗試在我的應用程序中模擬這個答案,但它不起作用。

#here's my data
stack_qn <- structure(list(country = c("Country1", "Country3", "Country2", 
"Country4", "Country9", "Country1", "Country2", "Country2", "Country8", 
"Country2", "Country5", "Country6", "Country5", "Country7", "Country9", 
"Country5", "Country3", "Country6", "Country4", "Country5"), 
    `2012` = c(0, 89, 0, 0, 0, 7, 0, 1, 0, 0, 0, 0, 0, 42, 60, 
    0, 0, 53, 213, 0), `Types of product` = c("product1", "product1", 
    "product1", "product1", "product1", "product2", "product2", 
    "product3", "product3", "product4", "product4", "product4", 
    "product6", "product6", "product6", "product7", "product7", 
    "product7", "product8", "product8")), class = c("spec_tbl_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -20L), spec = structure(list(
    cols = list(country = structure(list(), class = c("collector_character", 
    "collector")), `2012` = structure(list(), class = c("collector_double", 
    "collector")), `Types of product` = structure(list(), class = c("collector_character", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
    "collector")), skip = 1), class = "col_spec"))

#here's what I tried
library(shiny)
library(DT)


jsCode <- "function(row, data, start, end, display) {var api = this.api(), data;$( api.column(1).footer() ).html('Total: ' + MYTOTAL);}"

# Workaround
getTotal <- function(data,index){

  if(index < 1 || index > ncol(data)){
    return("")
  }
  col <- data[,index]
  col <- gsub("[$]","",col)
  col <- gsub("[,]","",col)
  col <- suppressWarnings(as.numeric(col))
  if(all(is.na(col))){
    return("")
  }
  sum(col)
}


ui <- function(){
  fluidPage(
    sidebarLayout(
      sidebarPanel(numericInput("nums", label = "Num Input", value = 1, min = 1, max = 10)),
      mainPanel(dataTableOutput("mytable"))
    )
  )
}

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

  Total <- reactive({
    getTotal(stack_qn,2)
  })

  cont <- htmltools::withTags(table(
    tableHeader(names(stack_qn)),tableFooter(names(stack_qn))
  ))

  output$mytable <- DT::renderDataTable(  {
    jsCode <- sub("MYTOTAL",Total(),jsCode)
    DT::datatable(stack_qn,
                  container = cont,
                  caption = tags$caption("Example"), 
                  filter = "none", 
                  rownames = F,
                  options = list(autoWidth = T, 
                                 pageLength = 10, 
                                 scrollCollapse = T,
                                 dom = 'lftp', 
                                 footerCallback = JS(jsCode))
    )
  }
  )
}

shinyApp(ui = ui, server = server)

當我運行應用程序時,什么也沒有發生。 非常感謝任何有關如何獲得要顯示的數字列的總和的幫助。

我意識到我必須將我的數據轉換為 dataframe 才能工作,即

stack_qn<-as.data.frame(stack_qn)

暫無
暫無

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

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