[R] Sweave data-figure coupling

Philipp Pagel p.pagel at wzw.tum.de
Mon Jan 5 21:38:57 CET 2009


On Mon, Jan 05, 2009 at 01:52:00PM -0600, Sebastian P. Luque wrote:
> <<binom-sim-fig, fig=TRUE, include=FALSE, height=3, echo=FALSE>>=
> layout(matrix(1:2, ncol=2)); par(mar=c(5, 4, 2, 1), cex=0.75)
> matplot(thetas, cbind(prior, lik, post), type="l", lty=c(2, 1, 1),
>         xlab="theta", ylab="probability density")
> lik <- dbinom(60, 100, thetas)
> lik.p <- prior * lik
> post <- lik.p / sum(lik.p)
> 
> matplot(thetas, cbind(prior, lik, post), type="l", lty=c(2, 1, 1),
>         xlab="theta", ylab="probability density")
> @
> 
> \includegraphics[width=\linewidth]{test-binom-sim-fig}
> 
> 
> \end{document}
> ---<--------------------cut here---------------end--------------------->---
> 
> If the embedded chunks are evaluated directly in an R session, two
> different panel data are produced by layout(), as expected.  However,
> when weaving and latexing the file produces, then the two panels show
> the same data, corresponding to the last data set.  This doesn't happen
> if the data are much simpler, say using matplot() with simple sequences
> of numbers.  Any ideas what is causing this and how to get around it?

I was very confused, too when I first had this happen to me. The
reason is that chunks with fig=TRUE are executed three times by
default: once for the eps file, the pdf and the default device.
Accordingly, whenever you modify data in such a code chunk, the
results change with each round of execution.

The solution to the problem is either 

 - separating the manipulations from the plotting in two code chunks 
 - or keeping the modified values in a separate variable instead of 
   modifying the original.

In your example you are modifying 'lik' and 'post'. Just call the
modified versions likMod and postMod or something like this and
your problem will go away.

cu
	Philipp

-- 
Dr. Philipp Pagel
Lehrstuhl für Genomorientierte Bioinformatik
Technische Universität München
Wissenschaftszentrum Weihenstephan
85350 Freising, Germany
http://mips.gsf.de/staff/pagel




More information about the R-help mailing list