[Rd] [R] Sweave: Variables in code chunk headers

Duncan Murdoch murdoch at stats.uwo.ca
Sat Dec 1 21:56:25 CET 2007


I've moved this response to R-devel, because my contribution is more 
along those lines.  Michael, if this doesn't interest you, please let us 
know.

On 01/12/2007 2:38 PM, Michael Hoffman wrote:
> Dieter Menne wrote:
>> Michael Hoffman <b3i4old02 <at> sneakemail.com> writes:
>>
>>> I would like to be able to do something like this:
>>>
>>>    <<echo=F,fig=T,width=mywidth>>=
>>>    ...
>>>    @
>>>
>>> with mywidth set in a previous code chunk. Is there a way to do this in 
>>> Sweave?
>>>
>> Not in the <<>>, but you could set a hook for fig:
>>
>>
>> >From Sweave docs:
>>
>> If option "SweaveHooks" is defined as list(fig = foo), and foo is a function,
>> then it would be executed before the code in each figure chunk. This is
>> especially useful to set defaults for the graphical parameters in a series of
>> figure chunks.
> 
> Thanks. I guess what I really want to do is switch between one of two 
> settings. Only one value can be in the defaults, and I would like some 
> way of setting the other value. This might not be easily possible, but I 
> thought I would ask.

My understanding is that Michael wants to have the Sweave options in a 
chunk depend on a calculation happening in the underlying R session. 
This is hard to do with hooks, because they are run after the options 
have already been processed.

(His example of changing the width actually does have an ugly solution. 
  In the hook, close the graphics device and reopen it with the options 
you really want.  To find some of the parameters (e.g. the filename), 
you'll need to use parent.frame() to look at the locals of the Rweave 
driver.  Yuck.)

It would be much nicer if a hook could be called after the options have 
been parsed, but before they have been processed, and the hook was 
allowed to modify the options.  For example, something like

options(SweaveHooks = list(
   massageOptions = function(options) {
     options$width = mywidth
     return(options)
   }
))

Comments?

Duncan Murdoch



More information about the R-devel mailing list