The on.exit function is used within other functions to specify a command to be run when exiting the parent function. For instance, if plotting parameters are automatically adjusted in a function, use on.exit to adjust plotting parameters back to their original settings.
  • expr – An R expression or command.

Example. A couple of posts ago, I used the layout function to create a pair of box plots outside of a scatterplot. In doing so, I made adjustments to the plot margin setting via par(mar). Below, this previous code has been wrapped into a function that automatically creates a scatterplot with box plots along the edges of the plot. In the function, I change plotting parameters, but I also put the user’s settings back in place when the function is done via on.exit. The code below created two plots, one using the new scatterBox function and a second creating a simple scatterplot. Notice that the default plot settings are back in place for the creation of the simple scatterplot.
> scatterBox <- function(x, y, ...){
+   opar <- par("mfrow", "mar")
+   on.exit(par(opar))
+   mat <- matrix(c(1,2,0,3), 2)
+   layout(mat, c(3.5,1), c(1,3))
+   par(mar=c(0.5, 4.5, 0.5, 0.5))
+   boxplot(x, horizontal=TRUE, axes=FALSE)
+   par(mar=c(4.5, 4.5, 0.5, 0.5))
+   plot(x, y, ...)
+   par(mar=c(4.5, 0.5, 0.5, 0.5))
+   boxplot(y, axes=FALSE)
+ }
> set.seed(5)
> x <- rnorm(200)
> y <- 25 - 22*x + 5*x^2 + rnorm(200)
> #png("onexit.png")
> scatterBox(x, y)
> #dev.off()
> #png("onexitafter.png")
> plot(x, y)
> #dev.off()
In the above code, the set.seed function makes the code reproducible, and the png and dev.off functions (commented out above) were used to save each of the plots to files.

Leave a Reply