R:将警告消息输出到UI

R:将警告消息输出到UI,r,shiny,R,Shiny,警告消息在控制台中输出,但是如何让这些警告显示在UI中,以便用户可以在不查看控制台的情况下看到它们?您可以使用tryCatch存储警告对象。 然后,您可以将消息放在UI上的任何位置 library(shiny) ui <- fluidPage( actionButton("btn", "click me") ) server <- function(input, output) { observeEvent(input$btn, { #x <- (1:3 *

警告消息在控制台中输出,但是如何让这些警告显示在UI中,以便用户可以在不查看控制台的情况下看到它们?

您可以使用
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))
如果不希望运行相同的操作两次,则使用以下技巧()

库(闪亮)

ui我试图运行您的代码,但收到以下消息:警告:observeEventHandler中出错:对象“last.Warning”未找到。你在控制台中看到警告消息了吗?是的,当我按下actionButton时,闪亮的应用程序会关闭,并且警告在控制台中。编辑了我的答案。你能试试这个吗?如果这仍然不起作用,我希望看到
sessionInfo()
的结果。同样的问题。这是我的sessionInfo()
R版本3.4.0(2017-04-21)平台:x86_64-w64-mingw32/x64(64位)运行于:Windows>=8 x64(build 9200)矩阵产品:默认语言环境:[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 United United United stats graphics grDevices utils Dataset methods base通过命名空间加载(未附加):[1]编译器_3.4.0工具_3.4.0
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))
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))