A Note on missing()

(This article was first published on English Blog on Yihui Xie | 谢益辉, and kindly contributed to R-bloggers)

I had misunderstood the function missing() for several years. Originally I thought it only applies to an argument that does not have a default or user-specified value. For example, this is fairly easy to understand:

f = function(x) {
f()  # should be TRUE

One day I was surprised to find that this also returned TRUE:

f = function(x = 1) {

What?! x does have a default value 1; why is it considered missing? Then I realized missing() really meant “argument/value not passed” (to the function call).

Below is a yet more surprising fact that I discovered:

f = function(x) {
g = function(y) {
g()  # still returns TRUE

I was surprised because when g calls f(y), y does not exist, yet it still worked. It looks like we did pass y (whatever it really is) to f(), but f() sees nothing. Sounds like fun of lazy evaluation or something.

Anyway, I don’t recommend using missing(). It is fragile and you may break it unintentionally. Per its help page:

missing(x) is only reliable if x has not been altered since entering the function […]

What I often do is to set the defautl value to NA or NULL, and use is.na() / is.null() to test if the default value was explicitly changed by the user. Of course, this has a different meaning with missing(), but it is more robust. In particular, NA works better when the function is used in a vectorized call, e.g., mapply().

To leave a comment for the author, please follow the link and comment on their blog: English Blog on Yihui Xie | 谢益辉.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)