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

前端 未结 3 1655
梦谈多话
梦谈多话 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:37

    NULL is just another value you can assign to a variable. It's no different than any other default value you'd assign in your function's declaration.

    missing on the other hand checks if the user supplied that argument, which you can do before the default assignment - which thanks to R's lazy evaluation only happens when that variable is used.

    A couple of examples of what you can achieve with this are: arguments with no default value that you can still omit - e.g. file and text in read.table, or arguments with default values where you can only specify one - e.g. n and nmax in scan.

    You'll find many other use cases by browsing through R code.

提交回复
热议问题