R-函数参数中的椭圆(`...`)和`NULL` [英] R - Ellipse (`...`) and `NULL` in function parameters
问题描述
构想
examplefn <- function(x = NULL, ...){str(x)}
我正在尝试使用此函数来兑现隐式的 x = NULL
.请考虑以下内容:
I'm trying to get this function to honor the implicit x = NULL
. Consider the following:
对于同时使用 x
和 ...
的呼叫,此结果在预期的情况下出现:
For a call using both x
and ...
this results as expected in:
> examplefn(1,2)
num 1
如果使用显式的 x = NULL
,则该行为也符合预期:
If using an explicit x = NULL
, the behavior also is as expected:
> examplefn(x = NULL,2)
NULL
但是,当尝试(并期望从函数定义中使用 x = NULL
时,我得到:
However, when attempting (and expecting the usage of x = NULL
from the function definition, I get:
> examplefn(2)
num 2
简单地说,该调用是按参数顺序求值的,而忽略了 x = NULL
的定义.
Implying, that the call is evaluated by argument order, disregarding the x = NULL
definition.
如何预防后者?
推荐答案
仅当未提供 x
值时,才使用定义 x = NULL
.因此,在编写 examplefn(2)
时, R
读取的是 examplefn(x = 2)
(因为 x
是参数数字1)和结果.
The definition x = NULL
is only used if no x
value is provided. So when writing examplefn(2)
what R
reads is examplefn(x = 2)
(as x
is argument number 1) and thus the result.
如果您想避免这种情况,可以采取以下几种方法:
If you want to circumvent this, here are a few approaches:
1..通过创建两个函数
fun0 <- function (x, ...) str(x)
fun1 <- function (...) fun0(NULL, ...)
fun1(2)
# NULL
2..另一种方法是为您命名参数,例如
2. Another approach is by naming you arguments, e.g.
fun2 <- function (x = NULL, y) str(x)
fun2(y = 2)
# NULL
3..也许对您来说最方便的另一种方法是简单地对参数重新排序,请参见
3. Another way, maybe the most convenient for you, is simply to reorder the arguments, see
fun3 <- function (..., x = NULL) str(x)
fun3(2)
# NULL
4.最后,这也是一种(简单的)可能性-在函数内部设置 x<-NULL
4. Finally, here is also a (trivial) possibility - setting x <- NULL
inside the function
fun4 <- function (...) {
x <- NULL
str(x)
}
fun4(2)
# NULL
但是我假设您有理由希望 x
作为参数.
But I am assuming you have reasons to want x
to be an argument.
这篇关于R-函数参数中的椭圆(`...`)和`NULL`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!