Knitr global variable for R and LaTeX code blocks

I am trying to create a numerical variable (in code: called nClusters) that can be used in a knitr document both in fragments of R-code and in LaTeX. An example is given in the code below.

Here I initialize and set the nClusters numerical variable to 7. Later in the document, I call it in the R code snippet, and this seems to work fine. However, I then try to call it in the LaTeX section (outside the R code snippet), and this causes 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:

Current output

When the output should be:

Desired output

LaTeX , , 7, . , : knitr, R-, LaTeX?

+4
1

pgffor

\foreach <variables> in {<list>} <commands>

, . . LATEX- script, :

\begin{center}
\foreach \i in {2,3,...,C} {
  Hello \i\
}

[1] "This is number 2" [1] "This is number 3" [1] "This is number 4" [1] "This is number 5" [1] "This is
number 6" [1] "This is number 7"
Hello 2 Hello 3 Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ?
Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ?
Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ?
Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ?
Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ? Hello ?
Hello ? Hello ? Hello Hello A Hello B Hello C

2,3 C, , '?'

. R, Sexpr{}

\begin{center}
\foreach \i in {2,3,...,\Sexpr{nClusters}} {
  Hello \i\
}

correct answer

0
source

All Articles