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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With