I’m trying to use possibly() to print the argument x as a message when the function sum() fails.
library(purrr)
t <- function(x) {
p <- possibly(sum, otherwise = message(x))
p(x)
}
However, I would not expect the below to retrieve any message, since sum() doesn’t fail:
> t(1)
1
[1] 1
Instead, the script below works as expected: sum() fails, thus t() prints the message ‘a’
> t('a')
a
NULL
>Solution :
As noted in the other answer, possibly simply does something quite different from what you want.
What you want is tryCatch (part of base R):
t <- function(x) {
tryCatch(sum(x), error = function (.) message(x))
}
t(1)
# [1] 1
t('a')
# a