Is it possible to stop executing of R code inside shiny (without stopping the shiny process)?

前端 未结 5 817
夕颜
夕颜 2020-12-03 03:26

Let\'s say I have a shiny app that has a function that can take a long time to run. Is it possible to have a \"stop\" button that tells R to stop the long-running call, wit

5条回答
  •  失恋的感觉
    2020-12-03 04:00

    Provided you can split the heavy duty calculations into several parts, or have access to the part of the code that is involved in the computation, you can insert a breaker part. I implemented this in a Shiny app that listens for a button press before continuing with the rest of the calculation. You can run the app from R by

    library(shiny)
    runGitHub("romunov/shinyapps", subdir = "breaker")
    

    or copy/paste the code into a server.R and ui.R and run it using runApp().

    #ui.R
    library(shiny)
    
    shinyUI(fluidPage(
    
      titlePanel("Interrupting calculation"),
    
      sidebarLayout(
        sidebarPanel(
          sliderInput(inputId = "num.rows", 
                      label = "Generate number of rows",
                      min = 1e1,
                      max = 1e7,
                      value = 3e3),
          actionButton(inputId = "ok", label = "Stop computation")
        ),
        mainPanel(
          verbatimTextOutput("result")
        )
      )
    ))
    
    #server.R
    library(shiny)
    
    shinyServer(function(input, output) {
      initial.ok <- 0
    
      part1 <- reactive({
        nr.f <- floor(input$num.rows/2)
        out1 <- data.frame(col = sample(letters[1:5], size = nr.f, 
                                        replace = TRUE), 
                           val = runif(nr.f))
        out1
      })
    
      part2 <- reactive({
    
        nr.c <- ceiling(input$num.rows/2)
        out2 <- data.frame(col = sample(letters[1:5], size = nr.c, 
                                        replace = TRUE),
                           val = runif(nr.c))
        out2
      })
    
      output$result <- renderPrint({
    
        out1 <- part1()
    
        if (initial.ok < input$ok) {
          initial.ok <<- initial.ok + 1
          stop("Interrupted")
        }
    
        out2 <- part2()
        out <- rbind(out1, out2)
    
        print("Successful calculation")
        print(str(out))
      })
    })
    

提交回复
热议问题