I would like to overwrite a not very helpful error message from a base R function and replace it with a custom error message. How could I achieve this?
To clarify, assume that I evaluate the following expression "a" + "b". Because I am trying to add two characters, R will complain and return "Error in "a" + "b" : non-numeric argument to binary operator".
Is there a way to catch this exact error message, and return a clearer error message, e.g. "You are trying to add two factors - this is not allowed"?
I suppose a starting point would be to work with the try function and grepl:
a <- try("a" + "a", silent = TRUE)
if(inherits(a, "try-error")){
cond <- sum(grepl("non-numeric argument to binary operator", deparse(a), fixed = TRUE)) > 0
if(cond){
stop("You are trying to add two characters. This is not allowed.")
}
}
But maybe there is a more 'generic' or 'elegant' way to do this?