Test if an argument of a function is set or not in R

Solution 1:

You use the function missing() for that.

f <- function(p1, p2) {
    if(missing(p2)) {
        p2=p1^2
    }
    p1-p2
}

Alternatively, you can set the value of p2 to NULL by default. I sometimes prefer that solution, as it allows for passing arguments to nested functions.

f <- function(p1, p2=NULL) {
    if(is.null(p2)) {
        p2=p1^2
    }
    p1-p2
}

f.wrapper <-function(p1,p2=NULL){
    p1 <- 2*p1
    f(p1,p2)
}
> f.wrapper(1)
[1] -2
> f.wrapper(1,3)
[1] -1

EDIT: you could do this technically with missing() as well, but then you would have to include a missing() statement in f.wrapper as well.

Solution 2:

In a case like this you can also use something like this:

f <- function(p1, p2 = p1 ^ 2) {
    p1-p2
}

See the part on Lazy evaluation at http://adv-r.had.co.nz/Functions.html