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

后端 未结 3 2081
后悔当初
后悔当初 2020-12-02 12:56

I have a function f that takes two parameters (p1 and p2):

If for the parameter p2 no value was passed to the fun

相关标签:
3条回答
  • 2020-12-02 13:18

    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.

    0 讨论(0)
  • 2020-12-02 13:25

    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

    0 讨论(0)
  • 2020-12-02 13:33

    I think '?missing' should do it.

    0 讨论(0)
提交回复
热议问题