1

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.

2
  • 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. Apr 30, 2012 at 17:41
  • Please add a minimal working example (MWE) that illustrates your problem. Also your \ifftoggle lacks the ‘false’-part.
    – Speravir
    Apr 30, 2012 at 17:42

1 Answer 1

1

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

Your approach has two problems:

  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.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .