R: catch message, return result (efficiently) -
consider function:
hello_world <- function() { message("hello world") "goodbye world" }
with constraint of being allowed call function once (e.g. expensive computation), how value function call and catch message (for handling)? i'm thinking of caching value in environment of trycatch()
call, can't work out how it.
here 2 non-examples:
# 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() } )
here example using 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 you") "goodbye world" } messagehandler(hello_world2) #[[1]] #[1] "goodbye world" # #$messages #[1] "hello world" "how you"
note catch warnings , message stop
, i.e., sent stderr()
.
Comments
Post a Comment