Skip to content

temporarily modify par values?

6 messages · Jim Ottaway, Romain Francois, Gabor Grothendieck

#
Is there some sort of 'with.par' function that temporarily changes par
parameters and then re-sets them so that instead of doing things such as

opar <- par(mar=c(4.1,4.1,4.1,8),...)

<do things>

par(opar)

you can do something like

with.par(mar=c(4.1,4.1,4.1,8),..., 
    <do things>)

where all but the last argument are parameters for par, and the last is
evaluated with opar <- par(...) and par(opar) wrapped around it?



Yours sincerely,
#
Jim Ottaway wrote:
Hi,

"with" is generic, so you could do something like that:

 > par <- function( ... ) structure( graphics::par( ... ), class = "par" )
 > with.par <- function( data, expr, ... ){
+    old.par <- data
+    expr
+    invisible( par( old.par ) )
+ }
 > with( par( mar = c(0,0,0,0) ), plot( 1:10, 1:10 ) )
 > plot( 1:10, 1:10)

Romain
#
That looks promising, thank you very much.

Yours sincerely,
#
It would be nice to add exception handling to this, to clean up on
error. Something like unwind-protect in Lisp.

Here's a naive implementation:


 with.par <- function(data, expr, ... ){
   olderror <- getOption("error")
   options(error=function () {
     par(old.par)
     options(error=olderror)
   })
   old.par <- data
   expr
   options(error=olderror)
   invisible(par(old.par))
 }

Is this a reasonable way to do such things? [I'm new to this kind of
stuff in R]

Or is there a 'with.error.handler' or 'with.unwind.protection' wrapper?
;-)

Yours sincerely,
#
Here is a minor variation:

par <- function( ... ) structure( graphics::par( ... ), class = "par" )
with.par <- function( data, expr, ... ) {
   on.exit(par(old.par, no.readonly = TRUE))
   old.par <- data
   invisible(expr)
}

which returns expr invisibly so that this works:

bp <- with(par(mar = c(4, 1, 1, 1)), boxplot(1:10))

On Sat, Apr 4, 2009 at 7:40 AM, Romain Francois
<romain.francois at dbmail.com> wrote:
#
Thank you very much, that looks like a better way of cleaning up with an
error too than my attempt.


Yours sincerely,