12

Is it possible to download objects in shiny without having to create a separate, redundant, instance of that object within the downloadHandler() call? For example, consider the following example:

ui.R

library(shiny)

shinyUI(pageWithSidebar(
  headerPanel("Simple Example"),

  sidebarPanel(
    textInput("options","Enter some content:",""),
    submitButton("Go")
  ),

  mainPanel(
    tableOutput("dataTable"),
    downloadButton('downloadData','Save Data as CSV File')
  )
))

server.R

library(shiny)

shinyServer(function(input, output) {
  makeQuery <- reactive({
      if(input$options == ""){
        return("Enter some options")
      }
      else {
        return(input$options)
      }
  })

  runQuery <- function(query){
    dat <- data.frame(v1=rep(query,5))
    return(dat)
  }

  output$dataTable <- renderTable({
    query <- makeQuery()
    if(grepl("^Enter",query)){
      return(data.frame(Error=query))
    } else {
      return(runQuery(query))
    }
  },include.rownames=FALSE)

  output$downloadData <- downloadHandler(
    filename = c('data.csv'),
    content = function(file) {
      write.csv(runQuery(makeQuery()), file)
    }
  )

})

The issue I have with the above example is that I am running runQuery() within both the renderTable() and downloadHandler() calls. In this example there isn't really any extra overhead but in my real example this requires running a 5-10 minute process so it is extremely inefficient to call it twice whenever someone downloads the data.

Is there anyway that I can get around this issue by referencing an already created object in the downloadHandler() call or some other work around?

David
  • 9,284
  • 3
  • 41
  • 40
  • Can query be sped up at all? `data.table` or something? I don't think the problem is with download handler if your queries are taking that long.. – intra Jun 24 '13 at 19:50
  • Unfortunately not - it's a hive query to a database. – David Jun 24 '13 at 20:23

1 Answers1

18

Yes! Turn the query from a function that you call from two places, into a reactive expression that you access from two places. Reactive expressions cache their results automatically.

Joe Cheng
  • 8,001
  • 42
  • 37
  • Thanks Joe! I just moved the work from both makeQuery() and runQuery() into the same reactive function and that did the trick. – David Jun 25 '13 at 15:52
  • What about if you need to store a previously stored reactive value, such as rv$myResultDataFrame?? – aloplop85 Jul 31 '15 at 19:27