Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print an argument of a function when it fails?

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading