2015-10-27 6 views
5

エラーから使用する関数の名前を抽出します。私が持っていたのであれば:関数がエラーで使用されています(呼び出し元)

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 

しかし、関数名を取得する方法はありません。

答えて

8

$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" 
+0

大変ありがとうございます。 –

+0

Np、お手伝いをさせていただきます。 –

+0

待ってください - 答えが "NP"であると言っていますか? :-) –

関連する問題