我有两个字符列和一个数字列,我正在尝试计算该数字列的总和。我尝试在我的应用中模拟this答案,但无法正常工作。
#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)
当我运行该应用程序时,没有任何反应。非常感谢您对如何获得该数字列的总和进行显示的任何帮助。
答案 0 :(得分:0)
我意识到我必须将我的数据转换成数据框才能正常工作
stack_qn<-as.data.frame(stack_qn)