I am trying to create a numeric variable (in code: called nClusters) that can be used in a knitr document both in R code chunks and LaTeX. An example is in the code below.
Here, I initialize and assign the numeric variable nClusters to a value of 7. Later, in the document, I call upon it in a R code chunk, and that seems to work okay. However, I then try to call it in a LaTeX section (outside the R code chunk), and this is causing problems:
\documentclass{article}
\usepackage{float, hyperref}
\usepackage[margin=1in]{geometry}
\usepackage{pgffor}
\begin{document}
<<options, echo=FALSE>>=
nClusters = 7 # I only want to define nClusters once
library(knitr)
opts_chunk$set(concordance=TRUE)
@
<<echo=FALSE,eval=TRUE,results='asis'>>=
# Here the call to nClusters works
for (i in 2:nClusters){
print(paste("This is number",i))
}
@
% Here the call to nClusters does not work (but if I hardcode nClusters as 7 then it works)
\begin{center}
\foreach \i in {2,3,...,nClusters} {
Hello \i\
}
\end{center}
\end{document}
When I knit this, I get output that shows that the call to nClusters in LaTeX (outside the R chunks) does not work.
Is it possible to create a global variable in knitr that can be called in both the R code chunks and LaTeX parts?
Change your LaTeX line to
\foreach \i in {2,3,...,\Sexpr{nClusters}} {
R. Mark Sharp, Ph.D.
Director of Primate Records Database
Southwest National Primate Research Center
Texas Biomedical Research Institute
P.O. Box 760549
San Antonio, TX 78245-0549
Telephone: (210)258-9476
e-mail: msh...@TxBiomed.org
>
> --
> You received this message because you are subscribed to the Google Groups "knitr" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to knitr+un...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.