Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get function being used in error (from call)

Tags:

r

I want to extract the name of the function being used from an error. So if I had:

mean(letters)
"P" * 5

I'd want to extract "mean.default" and "*". I can get the call from the error as follows:

capturer <- function(x){
    tryCatch({
        x
    }, warning = function(w) {
        w
    }, error = function(e) {
        e
    })
}

capturer(mean(letters))$call
## mean.default(letters)

capturer("P" * 5)$call
## "P" * 5

But don't have a way to grab the function names.

like image 693
Tyler Rinker Avatar asked Feb 08 '23 16:02

Tyler Rinker


1 Answers

You can grab the function name part with $call[[1]]. We could also add a deparse argument to add the option of having the result returned as a string.

capturer <- function(x, deparse = FALSE) {
    out <- tryCatch({
        x
    }, warning = function(w) {
        w$call[[1]]
    }, error = function(e) {
        e$call[[1]]
    })
    if(deparse) deparse(out) else out
}

## these return a call
capturer("P" * 5)
# `*`
capturer(mean(letters))
# mean.default

## these return a character
capturer("P" * 5, deparse = TRUE)
# [1] "*"
capturer(mean(letters), deparse = TRUE)
# [1] "mean.default"
like image 74
Rich Scriven Avatar answered Feb 16 '23 03:02

Rich Scriven