Search code examples
rnull

How can I pass NULL as an argument in R?


I have a vector arguments, where some values are NA. I would like to pass these arguments sequentially to a function like this:

myFunction(argument = ifelse(!is.na(arguments[i]),
           arguments[i], NULL))

so that it will take the value in arguments[i] whenever it's not NA, and take the default NULL otherwise. But this generates an error.

If it makes any difference, the function in question is match_on(), from the optmatch package. The argument in question is caliper, because I would like to provide a caliper only when one is available (i.e. when the value in the vector of calipers is not NA). And the error message is this:

Error in ans[!test & ok] <- rep(no,  length.out = length(ans))[!test &  : 
replacement has length zero
In addition: Warning message:
In rep(no, length.out = length(ans)) :'x' is NULL so the result will be NULL 

Solution

  • You can use ?switch() instead of ifelse -

    myFunction(argument = switch(is.na(arguments[i]) + 1, arguments[i], NULL))
    

    Here's the help doc for switch -

    switch(EXPR, ...)

    Arguments

    EXPR an expression evaluating to a number or a character string.

    ... the list of alternatives. If it is intended that EXPR has a character-string value these will be named, perhaps except for one alternative to be used as a ‘default’ value.

    Details

    switch works in two distinct ways depending whether the first argument evaluates to a character string or a number.

    If the value of EXPR is not a character string it is coerced to integer. If the integer is between 1 and nargs()-1 then the corresponding element of ... is evaluated and the result returned: thus if the first argument is 3 then the fourth argument is evaluated and returned

    Basically, when argument is NA then EXPR evaluates to 2 which returns NULL and when it is not NA then EXPR evaluates to 1 and returns arguments[i].