考虑函数:
hello_world <- function() {
message("hello world")
"goodbye world"
}
只允许调用函数一次的约束(例如,它可能是一个昂贵的计算),我如何从函数调用和捕获消息(处理)中获得值?我正在考虑在tryCatch()
调用的环境中缓存值,但不知道如何做到这一点。
下面是两个非示例:
# example 1
tryCatch(
hello_world(),
message = function(x) {
cat("the message is: ", x$message, "n")
}
)
# example 2
tryCatch(
hello_world(),
message = function(x) {
cat("the message is: ", x$message, "n")
hello_world()
}
)
下面是一个使用sink
的例子:
messageHandler <- function(fun, ...) {
zz <- textConnection("foo", "w", local = TRUE)
sink(zz, type = "message")
res <- fun(...)
sink(type = "message")
close(zz)
#handle messages
list(res, messages = foo)
}
messageHandler(hello_world)
#[[1]]
#[1] "goodbye world"
#
#$messages
#[1] "hello world"
hello_world2 <- function() {
message("hello world")
message("how are you")
"goodbye world"
}
messageHandler(hello_world2)
#[[1]]
#[1] "goodbye world"
#
#$messages
#[1] "hello world" "how are you"
注意,这也将捕获来自stop
的警告和消息,即发送到stderr()
的所有内容。