在另一次完成后运行闪亮的反应

时间:2017-12-30 21:41:20

标签: r shiny

我有两个输出,一个打印和一个绘图。我想在按下运行按钮(工作)后执行打印,然后在打印完成时执行绘图部件。

原因是打印部件执行一些需要几分钟的计算,并且输出需要转到绘图命令。

简单示例:

library(shiny)

ui <- fluidPage(


  sidebarLayout(
    sidebarPanel(
      actionButton('run','Run')
    ),

    mainPanel(
      verbatimTextOutput("Descriptive"),
      plotOutput("plotData",width = "700px", height = "500px")
    )
  )
)

server <- function(input, output) {

  output$Descriptive <- renderPrint({

    if(input$run>0){

      return(isolate({
        cat('Number of rows:', nrow(mtcars))
        mpg2 <<- mtcars$mpg+3
        cyl2 <<- mtcars$cyl+3
      }))
    }else{return(invisible())}
  })


  #### RUN AFTER DESCRIPTIVE COMPLETES ####
  output$plotData <- renderPlot({
    plot(mpg2,cyl2)
  })


}

shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:1)

我建议你将变量存储为reactiveValues并使图依赖于它们。通过这种方式,您可以避免当前的全局分配,并使绘图更新依赖于其变量的变化。

看起来像这样:

  global <- reactiveValues(mpg2 = mtcars$mpg, cyl2 = mtcars$cyl, txt = "")

  observe({
    if(input$run > 0){
      Sys.sleep(5) # simulate minutes of calculating
      global$txt <- paste('Number of rows:', nrow(mtcars))
      global$mpg2 <- mtcars$mpg + 3
      global$cyl2 <- mtcars$cyl + 3
    }
  })

您的应用看起来像这样:

library(shiny)

ui <- fluidPage(


  sidebarLayout(
    sidebarPanel(
      actionButton('run','Run')
    ),

    mainPanel(
      verbatimTextOutput("Descriptive"),
      plotOutput("plotData",width = "700px", height = "500px")
    )
  )
)

server <- function(input, output) {
  global <- reactiveValues(mpg2 = mtcars$mpg, cyl2 = mtcars$cyl, txt = "")

  observe({
    if(input$run > 0){
      Sys.sleep(5) # simulate minutes of calculating
      global$txt <- paste('Number of rows:', nrow(mtcars))
      global$mpg2 <- mtcars$mpg + 3
      global$cyl2 <- mtcars$cyl + 3
    }
  })



  output$Descriptive <- renderPrint({
    if(nchar(global$txt)) return(global$txt)
  })


  #### RUN AFTER DESCRIPTIVE COMPLETES ####
  output$plotData <- renderPlot({
    plot(global$mpg2, global$cyl2)
  })


}

shinyApp(ui = ui, server = server)