在 ShinyApp 中使用下载处理程序下载数据时出现问题

Problem in downloading data using Download Handlers in ShinyApp

我的 mtcar 原始数据是使用 ShinyApp 中的下载处理程序下载的 而我希望 修改后的数据(使用 SelectInputs)通过处理程序下载。 我也附上了我的代码,请告诉我它们有什么问题。非常感谢:)

library(shiny)
library(tidyr)
library(dplyr)
library(readr)
library(DT)

data_table <- mtcars

# Define UI
ui <- fluidPage(

downloadButton('downLoadFilter',"Download the filtered data"),

selectInput(inputId = "cyl", 
          label = "cyl:",
          choices = c("All",
                      unique(as.character(data_table$cyl))),
          selected = "4", 
          multiple = TRUE),

selectInput(inputId = "vs", 
          label = "vs:",
          choices = c("All",
                      unique(as.character(data_table$vs))),
          selected = "1", 
          multiple = TRUE),

DT::dataTableOutput('ex1'))

server <- function(input, output) {

thedata <- reactive({
if(input$cyl != 'All'){
  return(data_table[data_table$cyl == input$cyl,])
}

else if(input$vs != 'All'){
  return(data_table[data_table$vs == input$vs,])
}

else{
  return(data_table)
}
})

output$ex1 <- DT::renderDataTable(DT::datatable(filter = 'top',
                                              escape = FALSE, 
                                              options = list(pageLength = 
10, scrollX='500px',autoWidth = TRUE),{
                                                thedata() # Call reactive 
thedata()
                                              }))


output$downLoadFilter <- downloadHandler(
filename = function() {
  paste('Filtered data-', Sys.Date(), '.csv', sep = '')
},
content = function(path){
  write_csv(thedata(),path) # Call reactive thedata()
})}

shinyApp(ui = ui, server = server)

您仅在 renderDataTable 内更新 thedata()。您需要使其成为反应式,然后将其用于呈现为 DataTable 并被下载。 将您的服务器更改为:

# Define server logic
server <- function(input, output) {

  thedata <- reactive({
    if(input$cyl != 'All'){
      return(data_table[data_table$cyl == input$cyl,])
    }
    else{
      return(data_table)
    }
  })

output$ex1 <- DT::renderDataTable(DT::datatable(filter = 'top',
                                                  escape = FALSE, 
              options = list(pageLength = 10, scrollX='500px',autoWidth = TRUE),{
                                 thedata() # Call reactive thedata()
                               }))


output$downLoadFilter <- downloadHandler(
    filename = function() {
      paste('Filtered data-', Sys.Date(), '.csv', sep = '')
    },
    content = function(path){
      write_csv(thedata(),path) # Call reactive thedata()
    })}