[英]R Shiny: Output warning messages to UI
控制台中会输出警告消息,但如何让这些警告显示在UI中,以便用户无需查看控制台即可看到它们?
You can use tryCatch
to store a warning object. 您可以使用
tryCatch
存储警告对象。 You can then put the message anywhere on your UI. 然后,您可以将消息放在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))
If the operation is not heavy, an easy way is to run it twice: once with tryCatch
and the other without. 如果操作不重,一个简单的方法是运行两次:一次使用
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))
If running the same operation twice is not desirable, then use the following trick ( See this SO thread ) 如果不希望运行两次相同的操作,那么使用以下技巧( 参见此SO线程 )
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.