athlonshi
athlonshi

Reputation: 1821

Load files only once in R shiny server end

If the data file does not change but the model parameter changes, is there any way to only load the data file (uploaded by user) once in shiny server end? This is to say, when the file is uploaded and read by the R code, every time the user change the model parameter through web UI, the code does not reload the data file. I am very new to R shiny. I could not find any example. Thanks!

Upvotes: 1

Views: 1926

Answers (1)

mlegge
mlegge

Reputation: 6913

Shiny is pretty smart.

It knows when it needs to do something again and when it doesn't. This is a case when Shiny knows it doesn't need to reload the file, changing the parameter does not prompt a reload.

library(shiny)

options(shiny.maxRequestSize = 9*1024^2)

server <- shinyServer(function(input, output) {


  data <- eventReactive(input$go, {
    validate(
      need(input$file1, "Choose a file!")
    )

    inFile <- input$file1

    read.csv(inFile$datapath, header = input$header,
             sep = input$sep, quote = input$quote)
  })

  output$plot <- renderPlot({
    set <- data()
    plot(set[, 1], set[, 2] * input$param)
  })
})


ui <- shinyUI(fluidPage(
  titlePanel("Uploading Files"),
  sidebarLayout(
    sidebarPanel(
      fileInput('file1', 'Choose file to upload',
                accept = c(
                  'text/csv',
                  'text/comma-separated-values',
                  'text/tab-separated-values',
                  'text/plain',
                  '.csv',
                  '.tsv'
                )
      ),
      tags$hr(),
      checkboxInput('header', 'Header', TRUE),
      radioButtons('sep', 'Separator',
                   c(Comma=',',
                     Semicolon=';',
                     Tab='\t'),
                   ','),
      radioButtons('quote', 'Quote',
                   c(None='',
                     'Double Quote'='"',
                     'Single Quote'="'"),
                   '"'),
      tags$hr(),
      p('If you want a sample .csv or .tsv file to upload,',
        'you can first download the sample',
        a(href = 'mtcars.csv', 'mtcars.csv'), 'or',
        a(href = 'pressure.tsv', 'pressure.tsv'),
        'files, and then try uploading them.'
      ),
      actionButton("go", "Load File and plot"),
      sliderInput("param", "Parameter", 0, 1, value = 0.1, step = 0.1, animate = TRUE)

    ),
    mainPanel(
      tableOutput('contents'),
      plotOutput("plot")
    )


  )
))

shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions