by Guangming Lang
~1 min read

Categories

  • 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.

myfun = function(x){
        on.exit(print("first"))
        on.exit(print("second"), add = TRUE)
        return(x)
}
myfun(2)
## [1] "first"
## [1] "second"
## [1] 2

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

fun = function(x){
        on.exit(print("first"))
        on.exit(print("second"))
        return(x)
}
fun(2)
## [1] "second"
## [1] 2

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.