Doctor
Doctor

Reputation: 59

Problem in downloading data using Download Handlers in ShinyApp

My original data of mtcar gets downloaded using Download Handlers in ShinyApp whereas i want the the modified data (using SelectInputs) to be downloaded through Handlers. I have attached my codes as well, please let me know whats wrong with them. Many thanks:)

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)

Upvotes: 0

Views: 59

Answers (1)

Vishesh Shrivastav
Vishesh Shrivastav

Reputation: 2139

You are updating thedata() only inside your renderDataTable. You need to make it a reactive and then use it for being rendered as DataTable and being downloaded. Change your server to:

# 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()
    })}

Upvotes: 1

Related Questions