4

针织专家,

背景:使用 knitr 报告带有许多嵌入式图表的报告。在报告的正文中,所有合适的只是图表,而不是代码。

例如:

```{r graph_XYZ_subset, echo = FALSE, message = TRUE, 
                        fig.cap = "Text that explains the graph"}

graph.subset <- ggplot() + ...

```

这部分工作得很好。

但是,需要显示代码的关键部分(例如,关键统计分析和关键图形生成)......但在附录中。

这导致了这个问题:有没有办法将 knitr 块从脚本的早期部分复制到后面的部分?

为确保准确性,附录中的代码最好列出(显示)报告中实际执行的所有代码。

例如:

# ADDENDUM - Code Snippets

### Code to Generate Subset Graph

\\SOMEHOW COPY the code from graph_XYZ_subset to here without executing it.

### Code to Compute the Mean of Means of the NN Factors

\\Copy another knitr chunk which computes the mean of means, etc.

### And So On...

\\Copy chunks till done

* * * * * * * * 

有任何想法吗?knitr 中有没有办法执行这些类型的块副本?

4

1 回答 1

2

有几个选项,其中四个是 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块选项来跳过某些块。

于 2015-08-22T14:22:25.503 回答