【问题标题】:R Shiny: Output warning messages to UIR Shiny:向 UI 输出警告消息
【发布时间】:2017-06-23 13:15:52
【问题描述】:

警告消息在控制台中输出,但如何让这些警告出现在 UI 中,以便用户无需查看控制台即可看到它们?

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您可以使用tryCatch 来存储警告对象。 然后,您可以将消息放在 UI 上的任何位置。

    library(shiny)
    
    ui <- fluidPage(
      actionButton("btn", "click me")
    )
    
    server <- function(input, output)
    {
      observeEvent(input$btn, {
        #x <- (1:3 * 1:2)  # this generates a warning
        #warning("manually generated warning message")
        #mess <- names(last.warning)
        a <- tryCatch(warning(Sys.time()), warning=function(w) { w })
        mess <- a$message
        showNotification(mess)
      })
    }
    
    runApp(list(ui=ui, server=server))
    

    获取消息和价值

    如果操作不繁重,一个简单的方法是运行两次:一次使用tryCatch,另一次不使用。

    library(shiny)
    
    ui <- fluidPage(
      actionButton("btn", "click me")
    )
    
    server <- function(input, output)
    {
      observeEvent(input$btn, {
    
        x <- tryCatch(1:3 * 1:2, warning=function(w) { w })
        if (inherits(x, "simpleWarning")) {
          mess <- x$message
          showNotification(mess)
          x <- 1:3 * 1:2
        }
        print(x)
      })
    }
    
    runApp(list(ui=ui, server=server))
    

    如果不希望两次运行相同的操作,则使用以下技巧 (See this SO thread)

    library(shiny)
    
    ui <- fluidPage(
      actionButton("btn", "click me")
    )
    
    server <- function(input, output)
    {
      withWarnings <- function(expr) {
        myWarnings <- NULL
        wHandler <- function(w) {
          myWarnings <<- c(myWarnings, list(w))
          invokeRestart("muffleWarning")
        }
        val <- withCallingHandlers(expr, warning = wHandler)
        list(value = val, warnings = myWarnings)
      } 
    
      observeEvent(input$btn, {
        x <- withWarnings(1:3 * 1:2)
        if (!is.null(x$warnings)) {
          for (w in x$warnings) showNotification(w$message)
    
        }
      })
    }
    
    runApp(list(ui=ui, server=server))
    

    【讨论】:

    • 我尝试运行您的代码,但收到此消息:警告:observeEventHandler 中的错误:找不到对象“last.warning”
    • 真的。您是否在控制台中看到警告消息?
    • 是的,当我按下 actionButton 时闪亮的应用程序会关闭,并且该警告在控制台中。
    • 编辑了我的答案。你能试试这个吗?如果这仍然不起作用,我想看看sessionInfo() 的结果。
    • 同样的问题。这是我的 sessionInfo() R version 3.4.0 (2017-04-21) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows &gt;= 8 x64 (build 9200) Matrix products: default locale: [1] LC_COLLATE=English_United States.1252 [2] LC_CTYPE=English_United States.1252 [3] LC_MONETARY=English_United States.1252 [4] LC_NUMERIC=C [5] LC_TIME=English_United States.1252 attached base packages: [1] stats graphics grDevices utils datasets methods base loaded via a namespace (and not attached): [1] compiler_3.4.0 tools_3.4.0
    猜你喜欢
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    • 2012-08-25
    • 2015-08-07
    • 2011-05-06
    • 2020-08-10
    相关资源
    最近更新 更多