在R闪亮服务器端只加载一次文件

时间:2016-05-06 20:48:45

标签: r shiny

如果数据文件没有改变但模型参数发生了变化,有没有办法在闪亮的服务器端只加载一次数据文件(由用户上传)?这就是说,当文件被R代码上传和读取时,每次用户通过Web UI更改模型参数时,代码都不会重新加载数据文件。我对R闪亮很新。我找不到任何例子。谢谢!

1 个答案:

答案 0 :(得分:1)

Shiny非常聪明。

它知道什么时候需要再做一次,什么时候不做。这是Shiny知道它不需要重新加载文件的情况,更改参数不会提示重新加载。

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)