A Note on on.exit()

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

I have used on.exit() for several years, but it was not until the other day that I realized a very weird thing about it: you’d better follow the default positions of its arguments expr and add, i.e., the first argument has to be expr and the second has to be add.

on.exit(expr = NULL, add = FALSE)

If you do on.exit(add = TRUE, {...}), weird things can happen. I discovered this by accident. I have never switched the positions of expr and add before, and I was surprised that R CMD check failed on Travis with an error message that confused me in the beginning:

Error in on.exit(add = TRUE, if (file.exists(main)) { : 
  invalid 'add' argument

I was thinking why add = TRUE was considered invalid. Then I guessed perhaps the expression if (file.exists(main)) {} was treated as the actual value of add. So I switched to the normal order of arguments, and the error was gone.

I tested it a bit more and was totally confused, e.g., why was 1 printed twice below? I guess TRUE was not printed because add was treated as expr.

f = function() {
  on.exit(add = print(TRUE), print(1))
}
f()
# [1] 1
# [1] 1

I don’t have the capability to understand the source code in C, and I’ll leave it experts to explain the weird things I observed. For me, I’ll just never move add before expr again.

BTW, I don’t what the rationale is for the default add = FALSE in on.exit(), but I have not used add = FALSE for a single time, so I feel add = TRUE might be a better default. When I want to do something on exit, I almost surely mean do it in addition to the things that I assigned to on.exit() before, instead of cleaning up all previous tasks and only doing this one (add = FALSE).

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.

Sponsors

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)