これは実際には簡単ではありません。 (
f <- function(x, y = 1, ...){
cl <- match.call()
as.list(cl[-1])
}
str(f(1))
#> List of 1
#> $ x: num 1
str(f(1, 'foo'))
#> List of 2
#> $ x: num 1
#> $ y: chr "foo"
str(f(1, 'foo', list(3), fun = sum))
#> List of 4
#> $ x : num 1
#> $ y : chr "foo"
#> $ : language list(3)
#> $ fun: symbol sum
注match.call
だけ呼び出しをキャプチャし、デフォルトのパラメータに追加しません:あなたは機能を構築している場合は、それほど苦労せずに解析することができるmatch.call
との通話を、キャプチャすることができます最初の例ではy
はありません)。これらはf
が原始的ではないので、formals(f)
にアクセスすることができますので、完全な引数は
user_args <- f(1)
fun_args <- formals(f)
fun_args[names(user_args)] <- user_args
str(fun_args)
#> List of 3
#> $ x : num 1
#> $ y : num 1
#> $ ...: symbol
完成ドットではうまく機能しません。このアプローチを使用して作成することができ、彼らは十分なはずmatch.call
にそして自分自身を完了している場合。既存の関数に渡されたパラメータを抽出するには、match.call
というラッパーを書くことができますが、すべての関数を再構築するのは実用的ではなく、既存の関数を上書きしない限り、キャプチャした呼び出しは面白く見えます。限り機能が原始的ではないとして、あなたはformals
アプローチを可能にするためにquote
を使用することができ、しかし:
cl <- quote(rnorm(5, 2))
user_args <- as.list(cl[-1]) # subset call to only args
fun_args <- formals(as.character(cl[1])) # subset call to only function
names(user_args) <- names(fun_args)[seq(length(user_args))]
fun_args[names(user_args)] <- user_args
str(fun_args)
#> List of 3
#> $ n : num 5
#> $ mean: num 2
#> $ sd : num 1
別のアプローチは、rlangを使用することですその機能だけでなくプリミティブを扱う(fn_fmls(sum)
)、部品を抽出することができます(lang_fn
、lang_args
)、名前のない名前のパラメータを正確に(lang_standardize
)など、一緒にpurrrの新しいlist_modify
(DEV版)で、それはすべてがかなり無痛次のようになります。
library(rlang)
fun_call <- quo(rnorm(5))
fun_call
#> <quosure: frame>
#> ~rnorm(5)
default_args <- fn_fmls(lang_fn(fun_call))
str(default_args)
#> Dotted pair list of 3
#> $ n : symbol
#> $ mean: num 0
#> $ sd : num 1
user_args <- lang_args(lang_standardise(fun_call))
str(user_args)
#> List of 1
#> $ n: num 5
calling_args <- purrr::list_modify(default_args, user_args)
str(calling_args)
#> Dotted pair list of 3
#> $ n : num 5
#> $ mean: num 0
#> $ sd : num 1
私の知る限り、あなたは痛みの一種である、コールを保存し、それを解析する必要があると思います。 – alistaire
@alistaireが言ったように、あなたは 'Sys.call()'を使って関数内の呼び出しにアクセスすることができます...しかし、あなたの目標は何ですか? – Val