【问题标题】:R Shiny - How to break an lapply without stopping the app?R Shiny - 如何在不停止应用程序的情况下打破应用程序?
【发布时间】:2023-04-10 01:20:01
【问题描述】:

下面的应用程序包含一个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)

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

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

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    根据您应用中的具体要求,也许您可​​以使用“正常”循环并使用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)
      })
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 1970-01-01
      • 2017-05-03
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      相关资源
      最近更新 更多