4

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:

Current output

When the output should be:

Desired output

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?

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
  • I guess this is a `foreach` issue. Usually speaking, `R` variables are accessed with `$\Sexpr{nClusters}$` but not sure this can work in this case, you shoudl give it a try a say ! – ClementWalter May 16 '16 at 16:35

1 Answers1

0

When using pgffor,

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

is a comma-separated list of values. Anything can be used as a value. Here your variable is not passed to the LATEX part of the script, if you try your code with :

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

you get

[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

Which is a sequence starting with 2,3 and ending with C, I don't know what characters are printed out in the '?'

you produce exactly the same result. To evaluate the variable outside R chunk you need to use Sexpr{}

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

which produces

right answer

Cedric
  • 2,412
  • 17
  • 31