Search code examples
rcsvshinyzip

How do I access outputs in Shiny renderUI, and write these to multiple .csv / .zip


I am new to Shiny, apologies if this is obvious and has been asked numerous times, but I've been stuck on this for days. I've been modifying a dashboard to process analytical chemistry data i.e. it reads in multiple csv files, processes the data (smooths etc.) with various sliders and functions in Shiny, but does not save/download the processed data/output, which I've been trying to do. I don't seem to be able to access the "output" or processed data e.g. as a list of matrices, which I then write out as new .csv files. (I get "object of type 'closure' is not subsettable") I am competent in R, and have script which works well, but making this change to Shiny is proving problematic. How do I access the output data of detectedPeaks or baselineCorrectedSpectra to write to csv (or zip up the mutilple csv files)? Thank you.

#Just part of the relevant code - a long script
#server
 baselineCorrectedSpectra <- reactive({
    if (is.null(input$bc)) {
      method <- "SNIP"
      hws <- 100
    } else {
      method <- input$bc
      hws <- input$bcHws
    }

    return(lapply(smoothedSpectra(), function(y) {
      bl <- estimateBaseline(y, method=method, hws)
      intensity(y) <- intensity(y)-bl[, 2]
      return(y)

    }))
  })


  detectedPeaks <- reactive({
    return(detectPeaks(baselineCorrectedSpectra(), method=input$pdNoise,
                       halfWindowSize=input$pdHws, SNR=input$pdSNR))
  })


datasetInput <- reactive({
                switch(input$dtset,
                       "peaks" = detectedPeaks(),
                       "centroided" = baselineCorrectedSpectra())
        })

         output$DownloadZip <- downloadHandler(
   filename = function(){
     paste0("Results",".zip")
   },
   content = function(con){
     files <- c()
       tmpdir <- tempdir()
       setwd(tempdir())
 
     for (i in 1:length(s)){
    x<-as.matrix(datasetInput[[i]]) #This doesn't work,how do I access this data?
    y<-metaData(s[[i]])
    f<-(paste("processed", y, sep="_" )) 
    if(input$downloadType == ".csv")
    write.csv(x,f)
    else write.table(x,f)
    files<-c(x,files)
        }
     zip(zipfile=con, files=files)
  },
   contentType = "application/zip"
 )

Solution

  • The way to do it is below:

    x<-as.matrix(datasetInput()[[i]])