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
\begin{center}
\foreach \i in {2,3,...,nClusters} {
Hello \i\
}
\end{center}
\end{document}
When I knit this, I get the following output:
When the output should be:
The discrepancy is occurring in the LaTeX call to the variable, because if I hard-code in 7, then it works. Hence, my question is: Is it possible to create a global variable in knitr that can be called in both the R code chunks and LaTeX parts?