TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I know it is possible to use \Sexpr to pass information from an R chunk to LaTeX. For example,

a = 7
42 is the answer to 6 x \Sexpr{a}

Is there an equivalent way to pass information from LaTeX to R? For example,

\foreach \n in {1,...,7}{
share|improve this question
I very much doubt it since R is run first and as far as I know Sweave ignores everything outside of code chunks and \Sexpr{} constructs ... – Ben Bolker Oct 15 '12 at 13:24
You could try enabling 'write18' so that your LaTeX compile can generate an external file. You will have to open the file, write the value to it, and then close the file (in Windows, with Linux/Unix your have other options). Then in the following sweave/knitr chunk you open the file and read in the value. I have not attempted this so here may be other issues. – R. Schumacher Oct 15 '12 at 13:57
This would seem impossible in pure LaTeX Sweave, but something close would perhaps be possible using Org mode. – GTK Oct 15 '12 at 14:06
@GTK that sounds very interesting. Could you elaborate? – Tahnoon Pasha Oct 16 '12 at 1:48
up vote 5 down vote accepted

Sweave only allows one plot per code chunk, which might be the reason why you want a special loop in LaTeX, whereas knitr gives you all plots in a chunk. This normal loop in R will work with the knitr package:

<<echo = FALSE>>=
x = 1:10
for (n in 1:7) {
  plot(x, x^n-x)

If you want to write something with a loop, use R loops instead of LaTeX loops, which may look like this:

for (i in 1:10) {
  cat('this is plot ', i, ' and write whatever you want here')

Note with Sweave, you need results=tex instead of the knitr syntax results='asis'.

share|improve this answer
I had to add echo=FALSE to the second code chunk but, otherwise, this works great! – Chernoff May 16 '13 at 23:30
This answer shows how to do the example the author presented but doesn't answer the question "Is there a way to pass information from LaTeX to R" – JHowIX Oct 28 '15 at 16:35
@JHowIX I think the answer is no (at least not straightforward). – Yihui Oct 28 '15 at 19:08
@Yihui Good to know. Thank you sir! – JHowIX Oct 28 '15 at 19:36

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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