When to use missing versus NULL values for passing undefined function arguments in R, and why?

前端 未结 3 1668
梦谈多话
梦谈多话 2021-01-01 23:07

To date when writing R functions I\'ve passed undefined arguments as NULL values and then tested whether they are NULL i.e.

f1 <- function (x = NULL) {
           


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-01 23:31

    In my opinion, it is not clear when the limitation to missing applies. The documentation, as you quote, says that missing can only be used in the immediate body of the function. A simple example, though, shows that that is not the case and that it works as expected when the arguments are passed to a nested function.

    f1 = function(x, y, z){
      if(!missing(x))
        print(x)
      if(!missing(y))
        print(y)
    }
    
    f2 = function(x, y, z){
      if(!missing(z)) print(z)
      f1(x, y)
    }
    f1(y="2")
    #> [1] "2"
    f2(y="2", z="3")
    #> [1] "3"
    #> [1] "2"
    f2(x="1", z="3")
    #> [1] "3"
    #> [1] "1"
    

    I would like to see an example of a case when missing does not work in a nested function.

    Created on 2019-09-30 by the reprex package (v0.2.1)

提交回复
热议问题