是否可以在 R 中处理简单的消息?如果是,如何? [英] Is it possible to handle simple messages in R? If yes, how?

查看:44
本文介绍了是否可以在 R 中处理简单的消息?如果是,如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

处理警告或错误可以使用

To handle warnings or errors one can use

result = tryCatch({
    expr
}, warning = function(w) {
    warning-handler-code
}, error = function(e) {
    error-handler-code
}, finally = {
    cleanup-code
}

但是如果expr通过simpleMessage给出一个message,我怎么才能得到它?有类似的吗?:

but if expr gives a message through simpleMessage, how can I get it? Is there something like?:

message = function(m) {message-handler-code}

或者其他允许我捕获消息的函数?

Or another function which allows me to capture the message?

谢谢!

推荐答案

是的,您可以像使用 warningerror<一样使用 message = /代码>:

Yes, you can use message = just as you can with warning and error:

result = tryCatch({
    message("Hello world")
    1 + 1
}, message = function(m) {m}
)

result
#> <simpleMessage in message("Hello world"): Hello world
>

但是,您更有可能希望分别捕获结果和消息:

It's more likely however that you would want to capture your result and message separately:

result <- withCallingHandlers({
    message("Hello world")
    1 + 1
}, message = function(m) {
    lastMessage <<- m
    invokeRestart("muffleMessage")
})

result
#> [1] 2

if(exists("lastMessage")) message(lastMessage)
#> Hello world

这篇关于是否可以在 R 中处理简单的消息?如果是,如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆