【发布时间】:2015-09-29 11:33:12
【问题描述】:
我正在尝试创建一个可以在 R 代码块和 LaTeX 中的 knitr 文档中使用的数字变量(在代码中:称为 nClusters)。下面的代码中有一个示例。
在这里,我初始化数值变量 nClusters 并将其赋值为 7。稍后,在文档中,我在 R 代码块中调用它,这似乎可以正常工作。但是,然后我尝试在 LaTeX 部分(在 R 代码块之外)调用它,这会导致问题:
\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}
当我编织这个时,我得到以下输出:
什么时候输出应该是:
在对变量的 LaTeX 调用中出现差异,因为如果我在 7 中进行硬编码,那么它就可以工作。因此,我的问题是:是否可以在 knitr 中创建一个可以在 R 代码块和 LaTeX 部分中调用的全局变量?
【问题讨论】:
-
我猜这是
foreach问题。通常来说,R变量是通过$\Sexpr{nClusters}$访问的,但不确定这在这种情况下是否可行,你应该试一试!
标签: r latex global-variables knitr