The on.exit() Function

Master R

There’s an interesting little function in R called on.exit(). It can be used in your own function to perform some side effect. For example, in addition to returning a value, the following function uses on.exit() to also print two messages.

Note what happens if we remove add=TRUE from the second on.exit() usage.

We see “first” isn’t printed anymore.

To learn more about on.exit(), refer to Hadley’s book “Advanced R,” which can be obtained from Amazon.