2

I'm starting to learn R and Sweave and have spent the last couple of hours trying to figure out a problem that, according to my Google-fu, seems to be rather unknown or uncommon (as I found only two references to the problem).

Namely, when re-using a code chunk in Sweave, it seems you are not allowed any preceding whitespace. For example:

\documentclass{article}

\begin{document}

<<label=fig1boxplot, include=FALSE>>=
boxplot(mpg~cyl,data=mtcars) 
@

\begin{figure}
\centering
<<label=fig1, fig=TRUE, echo=FALSE>>=
<<fig1boxplot>>
@
\end{figure}

\end{document}

will not work as expected if there is any white space in front of any line beginning with << (errors vary depending on which line is indented). I found a work-around on the R developer mailing list that lets me indent the line where the chunk is reused (<<figboxplot>>) but still not any other chunk (<<label=...)

  • Why does Sweave not allow white space with reused code chunks, especially since the workaround seems very trivial to implement indeed?
  • How can I work around this problem and indent chunks (or any Sweave code for that matter) as much as I like?
mnel
  • 113,303
  • 27
  • 265
  • 254
ThomasH
  • 830
  • 1
  • 8
  • 23
  • 1
    Just to be clear, you're simply asking why the Sweave parser works the way it does? – joran Nov 25 '12 at 18:28
  • Actually, now that I've tried the workaround, it only solves the problem of indenting the `<>` line, but indenting any of the lines indicating the start of a chunk (`< – ThomasH Nov 25 '12 at 19:12

1 Answers1

3

The short answer is to use knitr instead, which allows indentation of code chunks.

For your question on Sweave, the answer is also short: it is by design (at least for now). My personal experience is that it is difficult to make it happen even if it is trivial in terms of implementation efforts as you said. That is a good reason for R add-on packages.

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
  • 2
    @ThomasH you are using an R version which was released more than _two years_ ago, which is terrible, and I strongly recommend you to update R, given that it is so easy to set up the repository on Ubuntu: http://cran.r-project.org/bin/linux/ubuntu/ For the error you saw, I recommend you to set the environment variable `R_LIBS_USER` in `~/.Renviron` to a writable directory, e.g. https://github.com/yihui/configuration/blob/master/.Renviron – Yihui Xie Nov 25 '12 at 21:13
  • Thanks for the help. I took the plunge and updated Ubuntu from 10.10 to 12.04 without my poor old laptop dying in the process and managed to get R to version 2.15.2 though I had to add `ppa:marutter/rrutter` to my sources list as it wouldn't update from 2.14 to 2.15 using the Irish CRAN mirror. – ThomasH Nov 29 '12 at 20:49
  • @ThomasH Great. Welcome to Precise Pangolin and R 2.15.2! – Yihui Xie Nov 29 '12 at 21:13