Jim Crozier
Jim Crozier

Reputation: 1418

knitr with latex forloop

Sorry if this is a stupid question, but does anyone know how to loop over R functions in knitr? My problem thus far is passing the variable from latex to the R function. I am trying to do something like this:

\documentclass{article}
\usepackage{forloop}
\newcounter{ind}  
\begin{document}

%Simple R function:
<<simpleRFun, results='asis' ,echo=FALSE>>=
simpleRFun = function(ind){
  set.seed(ind) ;
  plot(runif(100)) ;
}
@

%Run the function for value of 1
<<>>=
simpleRFun(1)
@

%Run the function for value of 2
<<>>=
simpleRFun(2)
@

%Loop over values of 1 and 2:
\forloop{ind}{1}{\value{ind} < 3}{
   \arabic{ind}
}

%Loop over values of 1 and 2 and pass to R function:
%Everything runs fine until this line:
\forloop{ind}{1}{\value{ind} < 3}{
<<>>=
simpleRFun(ind)
@
}

\end{document}

I am getting the following error:

Runaway argument?
 #### Error: object 'ind' not found \end {verbatim} \end {kframe} \end \ETC.
./knitr-minimal.tex:97: Paragraph ended before \@xverbatim was complete.
<to be read again> 
                   \par 
l.97 }

Thanks in advance for the help.

Upvotes: 2

Views: 1643

Answers (1)

Greg Snow
Greg Snow

Reputation: 49640

I don't think that you can do what you are trying to do (at least not in the way that you are trying to do it). The knitr function runs all the R code without doing anything with the LaTeX code, then you use LaTeX on the results and it does not run R for the R part.

Can you redo your loop to do the looping in R so that knitr puts the results of the loop into the LaTeX?

Either that or you need an extension to LaTeX that will run the R part for you.

Upvotes: 3

Related Questions