6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

メモ:Rの関数にデフォルト引数があるか無いかを判定する3つの方法 #rstatsj

Posted at

R の関数の各引数に対してデフォルト引数があるか無いかを判定したい。
例えば、次のような関数があったとする。

R
func <- function(x=1, y) x + y

この関数の引数 x にはデフォルト引数があるが、y にはデフォルト引数が無い。
関数のデフォルト引数を見るには、formals() 関数を使う。

R
default_args <- formals(func)
default_args
結果
$x
[1] 1

$y

こんな感じで、デフォルト引数があるかどうかは、人目で見れば一目瞭然である。
しかし、プログラム上で判定するには少し工夫がいる。

1. missing() を使う

関数内で引数に値が与えられたかどうかを判定する関数 missing() を使う。
ただし、そのままでは判定できず、いったん変数に代入する必要がある。

R
missing(default_args[["y"]])
結果
Error in missing(default_args[["y"]]) : invalid use of 'missing'
R
miss_arg <- default_args[["y"]]
missing(miss_arg)
結果
[1] TRUE

2. quote(expr = ) と比較する

quote(expr = ) によって引数なしの値を作ることができる。
これと同じかどうかで判定できる。

R
default_args[["y"]] == quote(expr = )
結果
[1] TRUE

missing() のときとは逆で、この方法では代入を行ってはならない。

R
miss_arg <- default_args[["y"]]
miss_arg == quote(expr = )
結果
Error: argument "miss_arg" is missing, with no default

3. よく見かける方法

R のコードを読んでいるとよく見かけるのが、次の方法である。

R
eval(substitute(missing(.), list(. = as.name("y"))), envir = default_args)
結果
[1] TRUE

R のコア関数内ではよくこの方法が使われている気がする。
この方法より、上で紹介した 2 つの方が簡単だと思うのだけど、これを使うメリットが何なのかはよく分かってない。

以上。

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?