Global variable in knitr not working for both R code Chunks and LaTeX

108 views
Skip to first unread message

Stella Johnson

unread,
Jul 13, 2015, 10:19:45 AM7/13/15
to kn...@googlegroups.com

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?

S johnson

unread,
Jul 13, 2015, 11:43:19 PM7/13/15
to Mark Sharp, kn...@googlegroups.com
Thank you! That is very curious. It does work.

However, when I put that back into my real code, it no longer works. The only difference is that my real code is more fleshed-out than my sample code. I have several more R code chunks in between where I am creating some of the data frames to be used etc. 

I receive an error in the \foreach \i in {2,3,...,\Sexpr{nClusters}} { part of my real code: "Error in eval(expr, envir, enclos) : object 'nClusters' not found"

Is there any other behavior regarding global variables in knitr that could cause this discrepancy? 

On Mon, Jul 13, 2015 at 2:28 PM, Mark Sharp <msh...@txbiomed.org> wrote:
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.







Reply all
Reply to author
Forward
0 new messages