2

I'm using some R code to import and manipulate a time series. The code takes some minutes to run and, as a result, it generates a relatively small time series.

Now, to prevent typesetting to take an annoying amount of time, I thought I could directly import the final result in R/Sweave but, at the same, I would like people that do not have the saved object to automatically generate it. Something like

\IfFileExists{"data.dat"}{
<<echo=FALSE>>=
##  import data ##
@

<<eval=FALSE>>=
##  code to generate data ##
@

}
{

<<>>=
##  code to generate data ##
@

<<echo=FALSE>>=
## save data in data.dat ##
@

}

The problem is that the Sweave compilation ignores the \IfFileExists and executes both chunks. Is there a way to prevent Sweave to execute chunk if a particular condition is satisfied (i.e. a file exists) ?

1

You do not need LaTeX for this, only R:

if (file.exists("data.dat")==TRUE) cat("yes") else cat ("no")
2
  • Yes, that's indeed the workaround I came up with, but it has the drawback of showing the if in the R code, which is something I don't really like (as the if is only related to the typesetting part, it's not something relevant that should be printed in the pdf). – Manlio Jan 16 '16 at 11:34
  • 1
    @Saphrosit Well, then put that part in a hided R chunk. With knitr options you can even deactivate the echo for selected lines only. Citing textually: "e.g. echo=2:3 means only echo the 2nd and 3rd expressions, and echo=-4 means to exclude the 4th expression" – Fran Jan 16 '16 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.