# Using toggles from etoolbox to switch Sweave Schunks of code on and off

I would like to use the toggles from etoolbox to direct Sweave to evaluate or not evaluate chunks of code. Example:

\newtoggle{FirstTime}
\toggletrue{FirstTime}
%\togglefalse{FirstTime}

\iftoggle{FirstTime}{
<<>
read.csv("My Big Fat Data file.csv") -> MyData
@
}


The idea would be to read in the data at the beginning of the work session and then \togglefalse so it would not need to be read again. I am using Eclipse and StatET, so object MyData would be resident in memory and accessible to R throughout the session.

However, the above code evaluates regardless of the toggle value.

I know I can achieve this result by changing eval=TRUE to eval=FALSE - but using toggles would be cleaner and give more flexibility.

-
Problem might be related to the @. Try adding \makeatletter before the \iftoggle and a \makeatother after the closing }. You also should have an additional {} at the end for the case where the \iftoggle evaluates to false. – Peter Grill Apr 30 '12 at 17:41
Please add a minimal working example (MWE) that illustrates your problem. Also your \ifftoggle lacks the ‘false’-part. – Speravir Apr 30 '12 at 17:42

I encourage you to try the knitr package, which does this job more elegantly. See section 3.5 "Evaluation of Chunk Options" in the manual: https://github.com/downloads/yihui/knitr/knitr-manual.pdf

1. Sweave will not recognize \iftoggle, because it does not analyze the TeX context; the tex document is processed purely as character strings -- whenever it sees <<>>=, it will treat the following lines as R code, regardless of if you have \iftoggle above the code chunk;
2. you write more code by inserting \iftoggle{FirstTime}{} around your code chunks, and this is how you can do it with less efforts in knitr:

\documentclass{article}

\begin{document}

<<controller>>=
# this variable controls if a chunk should be evaluated
dothis <- TRUE
@

<<chunk1, eval = dothis>>=
print('say hello world')
@

<<chunk2, eval = !dothis>>=
print('silence is gold')
@

\end{document}


If you find the syntax strange, you may read how knitr differs with Sweave; basically knitr makes your document really programmable.

-
Thanks. I'll check it out. – Placidia Apr 30 '12 at 21:18