修改 knitr 块中的外部 R 脚本

Modify external R script in a knitr chunk

我想知道是否可以挂钩 knitr 读取的外部 R 脚本中的代码。

具体来说,假设您有以下 R 文件

test.R

## ---- CarPlot
library(ggplot2)
CarPlot <- ggplot() +
    stat_summary(data = mtcars,
                 aes(x = factor(gear),
                     y = mpg
                     ),
                 fun.y = "mean",
                 geom = "bar"
                 )
CarPlot

假设您想在多个报告中使用此图表,但在其中一个报告中您希望图表有标题,而在另一个报告中您没有。

理想情况下,我希望能够使用相同的外部 R 脚本来执行此操作,这样我就不必更改多个 R 文件,以防我决定更改图形的某些内容。

我认为可能实现此目的的一种方法是将 fig.show 块选项设置为 hold——因为它将“hold all plots and output them in the very end of a code chunk”——然后将标题附加到情节是这样的:

test.Rnw

\documentclass{article}

\begin{document}

<<external-code, cache=FALSE,echo=FALSE>>=
read_chunk('./test.R')
@

<<CarPlot,echo=FALSE,fig.show='hold'>>=
CarPlot <- CarPlot + ggtitle("Plot about cars")
@

\end{document}

但是,这不起作用。虽然打印了情节,但我尝试附加的标题没有显示。

有什么方法可以做我想做的事吗?

您不想显示 test.R 创建的情节,因此您应该为该块设置 fig.show = 'hide'include = FALSE

<<external-code, cache=FALSE,echo=FALSE,fig.show = 'hide'>>=
read_chunk('./test.R')
@

想显示修改后的情节,所以你必须打印它:

<<CarPlot,echo=FALSE>>=
CarPlot <- CarPlot + ggtitle("Plot about cars")
CarPlot
@

fig.show = 'hold' 如果您有一个较大的代码块在中间打印一个图,但您不希望该图直到最后才显示在文档中,则使用

fig.show = 'hold'。它不适用于这种情况。