R Get函数在错误中使用(从调用)

R Get函数在错误中使用(从调用),r,R,我想从错误中提取正在使用的函数的名称。如果我有: mean(letters) "P" * 5 我想提取“mean.default”和“*”。我可以从错误中获得调用,如下所示: capturer <- function(x){ tryCatch({ x }, warning = function(w) { w }, error = function(e) { e }) } capturer(mean(lett

我想从错误中提取正在使用的函数的名称。如果我有:

mean(letters)
"P" * 5
我想提取
“mean.default”
“*”
。我可以从错误中获得调用,如下所示:

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

capturer您可以使用
$call[[1]]
获取函数名部分。我们还可以添加一个
deparse
参数来添加将结果作为字符串返回的选项

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"
capturer等等——你是说你的答案是“NP”完成的?:-)我的想法更像是“没有问题”;)