Skip to content
Prev 220944 / 398500 Next

Are there better ways to save and restore par() settings

On 14/05/2010 6:19 PM, David Winsemius wrote:
No, it applies to everything.  The general rule of "etiquette" is that 
if you change the par() settings, you should restore them when you're done.
Code contained in "on.exit" expressions is executed when the current 
function exits.  I would guess the first example didn't use this, 
because there's a fiction when running examples that they are run by the 
user at the command line:  so on.exit() would never execute.  (I don't 
know what happens if you put a naked on.exit() in example code; I would 
guess it would cause trouble, because it would interfere with the way R 
already handles the exit from running an example.) You need to read the 
comment, which says "At end of plotting, reset to previous settings:".  
The on.exit() wrapper is a way of ensuring that this happens when the 
code is in a function.  No matter how the function exits (even if it 
exits due to an error), R will attempt to run that code and restore the 
settings.

So it is safe to run the example code in almost any context, because it 
sets a par() value, then restores it.  But real code usually has 
something in between those two steps, and it may quit, or return from a 
function, or die due to an error.  The advice is to write things in a 
way that ensures that no matter what goes wrong, if you've changed the 
parameters, then you will change them back.

Does that make sense?

Duncan Murdoch