R - Ellipse (`…`) and `NULL` in function parameters

僤鯓⒐⒋嵵緔 提交于 2019-12-23 13:10:56

问题


Envision

examplefn <- function(x = NULL, ...){str(x)}

I'm trying to get this function to honor the implicit x = NULL. Consider the following:

For a call using both x and ... this results as expected in:

> examplefn(1,2)
num 1

If using an explicit x = NULL, the behavior also is as expected:

> examplefn(x = NULL,2)
NULL

However, when attempting (and expecting the usage of x = NULL from the function definition, I get:

> examplefn(2)
num 2

Implying, that the call is evaluated by argument order, disregarding the x = NULL definition.

How can the latter be prevented?


回答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. By creating two functions

fun0 <- function (x, ...) str(x) 
fun1 <- function (...) fun0(NULL, ...)
fun1(2)
# NULL

2. Another approach is by naming you arguments, e.g.

fun2 <- function (x = NULL, y) str(x)
fun2(y = 2) 
# NULL

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. Finally, here is also a (trivial) possibility - setting x <- NULL inside the function

fun4 <- function (...) {
  x <- NULL
  str(x)
}
fun4(2)    
# NULL

But I am assuming you have reasons to want x to be an argument.



来源:https://stackoverflow.com/questions/54436901/r-ellipse-and-null-in-function-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!