[Rd] [R] Sweave: Variables in code chunk headers
Duncan Murdoch
murdoch at stats.uwo.ca
Sun Dec 2 12:42:13 CET 2007
Michael Hoffman wrote:
> Duncan Murdoch wrote:
>
>
>> 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.
>>
>
> That would be really nice and allow some things I hadn't even imagined
> would be possible.
>
> But really I just would like the ability to set a variable statically
> and reuse it. Using a macro system like m4 would work, although I
> dislike the idea of adding yet another macro system to my poor document.
>
I put together a clunky way to handle that for a presentation last week;
it may be enough for you.
I leave the Sweave options at their defaults, but I have code chunks
that affect the appearance, and I run those without echoing to switch
between a couple of formats. For example, I have some pages that
display one figure, and others that display two. I use these
definitions at the beginning:
\SweaveOpts{height=5,width=10}
\setkeys{Gin}{width=\textwidth}
<<double, echo=FALSE, eval=FALSE>>=
options(SweaveHooks=list( fig=function() par(mfrow=c(1,2)) ))
@
<<single, echo=FALSE>>=
options(SweaveHooks=list( fig=function() par(mar=c(5,13,4,11)+0.1)) )
@
Then a plot would look something like this:
<<echo=FALSE>>=
<<double>>
set.seed(130)
@
<<fig=TRUE>>=
x <- rt(1000, 3)
qqnorm(x); qqplot(rnorm(1000), x)
@
The "single" versus "double" settings are persistent, and since most
plots were single, I'd probably follow this with
<<echo=FALSE>>=
<<single>>
@
This sets up very large margins on single plots, so they are
approximately centered within the fixed width display.
One other thing that would have helped with this approach would be a way
to include another file: then I wouldn't have to repeat those
definitions in every Rnw of the project.
Duncan Murdoch
More information about the R-devel
mailing list