Get function is used on error (from a call)

I want to extract the name of the function used from the error. Therefore, if I had:

mean(letters) "P" * 5 

I want to extract "mean.default" and "*" . I can get a 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 you have no way to capture function names.

+5
source share
1 answer

You can capture part of the function name with $call[[1]] . We could also add the deparse argument to add a parameter to get the result 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" 
+8
source

Source: https://habr.com/ru/post/1234616/


All Articles