首页 > 解决方案 > R Shiny - 如何在不停止应用程序的情况下打破应用程序?

问题描述

下面的应用程序包含一个在单击时actionButton触发的lapplylapply循环通过数字 2-4 并在 x %% 2 不为 0 时停止。是否可以在不lapply停止主应用程序的情况下中断?

library(shiny)

ui <- fluidPage(
  actionButton(inputId = "go", label = "Start"),
  div(id = 'placeholder')
)

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

  observeEvent(input$go, {

    lapply(2:4, function(x) {

      res = x %% 2

      if(res == 0){

        return(x)

      } else {

        insertUI('#placeholder', ui = tags$p('There was an error.'))

        stop('Error')
      }
    })
  })

}

shinyApp(ui = ui, server = server)

reqx %% 2 == 0不是一个选项,因为如果不满足条件,我需要在终止循环之前插入一些 UI 。

我在这里发现了一个类似的问题:Is it possible to stop execution of R code inside shiny (without stop the shiny process)? . 但它依赖于用户输入来停止执行,我不知道如何将它修改为这个例子。我也无法尝试修改它,因为parallel它不适用于 R 版本 3.6.0。我还看到了这里引用的这篇文章:https ://github.com/rstudio/shiny/issues/1398但我认为它也需要用户输入。

标签: rshiny

解决方案


根据您应用程序中的确切要求,也许您可​​以使用“正常”循环并使用break来停止循环执行。或者,您可以将其包装在一个try调用中:

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

  observeEvent(input$go, {

    try(lapply(2:4, function(x) {

      res = x %% 2

      if(res == 0){

        return(x)

      } else {

        insertUI('#placeholder', ui = tags$p('There was an error.'))

        stop('Error')
      }
    }), silent=T)
  })

}

推荐阅读