简体   繁体   中英

Run Shiny Reactive after Another Finishes

I have two outputs, a print and a plot. I would like to execute the print after the run button is pressed (working) and then when the print completes the plot part executes.

The reason for this is the print part does some calculations that take a few minutes and the output from that needs to go to the plot command.

Simple example:

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)

I would suggest you to store the variable as reactiveValues and make the plot dependent on them. By this you can avoid the current global assignment and also make the plot update dependent on a change in its variables.

It could look like this:

  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
    }
  })

Your app would look like this:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM