gpt4 book ai didi

r - 一种在knitr中复制 block 的方法?

转载 作者:行者123 更新时间:2023-12-01 03:39:03 25 4
gpt4 key购买 nike

针织专家,

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

例如:

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

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

```

这部分工作得很好。

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

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

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

例如:
# 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 中有没有办法执行这些类型的 block 副本?

最佳答案

有几个选项,其中四个是 listet 并在下面简要说明。易辉在How to reuse chunks的解释也可能有帮助。

\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}

Output

我通常更喜欢选项 4。这允许您将编程逻辑与编写文档分开。

地点 mychunk将被执行,图形将出现在 PDF 中,您只有 <<mychunk>>=在您的 Rnw文件,而不必费心生成图表的所有代码。开发代码也更容易,因为在交互式 session 中,您可以将所有代码放在一个位置,并且在从一个 block 转到下一个 block 时不必滚动报告的所有文本。

编辑:
上述选项的共同点是您需要手动维护要在附录中显示的 block 列表。这里有两个选项可以避免这种情况;不幸的是,两者都有一些缺点:

选项 1:自动创建所有已执行 block 的列表并显示其代码。

这可以使用 chunk hook 来实现注册所有 block 名称。在文档中的所有其他 block 之前包含以下 block :
<<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
@

在要显示代码的地方(例如在附录中),插入以下 block :
<<showCode, ref.label = unique(myChunkList), eval = FALSE>>=
@

不幸的是, block 之间没有边距或任何其他视觉分隔。

选项 2:并不总是需要使用 block Hook ,因为有函数 all_labels()返回所有 block 标签的列表。但是,您的文件中可能有未执行的 block ,您可能不想看到它们的代码。此外,选项 1 允许通过设置 recordLabel = FALSE 跳过某些 block 。在他们的 block 选项中。

关于r - 一种在knitr中复制 block 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32150930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com