有几个选项,其中四个是 listet 并在下面简要说明。Yihui 在如何重用块中的解释也可能有所帮助。
\documentclass{article}
\begin{document}
\section{Output}
<<mychunk, echo = FALSE>>=
print("Hello World!")
@
\section{Source code}
Option 1: Use an empty chunk with the same label.
<<mychunk, eval = FALSE>>=
@
Option 2: Embed in other chunk (no advantage in this case). Note that there is no equality sign and no at for the inner chunk.
<<myOtherChunk, eval = FALSE>>=
<<mychunk>>
@
Option 3: Use \texttt{ref.label}.
<<ref.label = "mychunk", eval = FALSE>>=
@
Option 4: Define the chunk in an external file you read in using \texttt{read\_chunk}. Then use Option 1--3 to execute the chunk (with \texttt{eval = TRUE}; default) or show it's code (with \texttt{eval = FALSE}).
\end{document}

我通常更喜欢选项 4。这允许您将编程逻辑与编写文档分开。
在这个地方mychunk
将被执行,并且图表将出现在 PDF 中,您只需要<<mychunk>>=
在您的Rnw
文件中,而不必为生成图表的所有代码而烦恼。开发代码也更容易,因为在交互式会话中,您将所有代码放在一个位置,并且在从一个块转到下一个块时不必滚动报告的所有文本。
编辑:上述选项的共同点是您需要手动维护要在附录中显示的块列表。这里有两个选项可以避免这种情况;不幸的是,两者都有一些缺点:
选项 1:自动创建所有已执行块的列表并显示其代码。
这可以使用chunk hook
注册所有块名称的 a 来实现。在文档中的所有其他块之前包含以下块:
<<echo = FALSE>>=
library(knitr)
myChunkList <- c()
listChunks <- function(before, options, envir) {
if (before) {
myChunkList <<- c(myChunkList, options$label)
}
return(NULL)
}
knit_hooks$set(recordLabel = listChunks) # register the new hook
opts_chunk$set(recordLabel = TRUE) # enable the new hook by default
@
在要显示代码的地方(例如在附录中),插入以下块:
<<showCode, ref.label = unique(myChunkList), eval = FALSE>>=
@
不幸的是,块之间没有边距或任何其他视觉分隔。
选项 2:并不总是需要使用块挂钩,因为有一个函数all_labels()
会返回所有块标签的列表。但是,您的文件中可能有未执行的块,您可能不想看到它们的代码。此外,选项 1 允许通过设置recordLabel = FALSE
块选项来跳过某些块。