使用 Knitr 和 LaTex 编写报告时加载 R 包

Load R packages when writing report with Knitr and LaTex

我有以下使用 Knitr 和 LaTeX 编写报告的组合系统,

  1. Rstudio 版本 0.99.473 和 R 版本 3.2.2
  2. Knitr_1.11
  3. MiKTeX 2.9
  4. Windows 7

示例 .Rnw 代码如下所示,我的问题是文本字符串 "latticeknitrstatsgraphicsgrDevicesutilsdatasetsmethodsbase" 是在 "Figure 1: Test" 的正下方创建的。我想知道如何摆脱它。

\documentclass[letterpaper]{article}
\title{An example}
\author{Me}
\date{\today{}}

<<setup, include=FALSE, cache=FALSE>>=
knit_hooks$set(myPackage = function(before, options, envir){
  if(before)
    library(lattice)  else NULL
})
@

\begin{document}
\maketitle
\newpage
\section{My section 1}
\begin{figure}
\caption{Test}\label{fig:GofBase}
<<myPackage=TRUE, echo=FALSE, results='asis', cache=TRUE, fig.show='hold', fig.align='center', warning=FALSE>>=
xyplot(rnorm(100)~rnorm(100))
@
\end{figure}

\end{document}

这是 "works for me"(也来自 RStudio)

的最小改动版本
\documentclass[letterpaper]{article}
\title{An example}
\author{Me}
\date{\today{}}

<<setup, include=FALSE, cache=FALSE, echo=FALSE>>=
knit_hooks$set(myPackage = function(before, options, envir){
  if(before)
    library(lattice)  else NULL
})
@

\begin{document}
%\SweaveOpts{concordance=TRUE}
\maketitle
\newpage
\section{My section 1}
\begin{figure}
\caption{Test}\label{fig:GofBase}
<<myPackage=TRUE, echo=FALSE, cache=FALSE, fig.show='hold', fig.align='center', warning=FALSE>>=
print(xyplot(rnorm(100)~rnorm(100)))
@
\end{figure}

\end{document}

我在第一个块中添加了 echo=FALSE,并从第二个块中删除了 results='asis'

由于问题提得不是很清楚,最小的例子也不是绝对的"minimal",这里是改进版:

问题

为什么下面的最小示例会在输出中添加类似 latticeknitrstatsgraphicsgrDevicesutilsdatasetsmethodsbase 的字符串?

\documentclass{article}

<<setup>>=
knit_hooks$set(myPackage = function(before, options, envir){

    if(before) library(lattice)
})
@

\begin{document}
<<myPackage=TRUE>>=
xyplot(rnorm(100)~rnorm(100))
@
\end{document}

回答

这与 lattice 无关,也不是 knitr 块挂钩的特殊功能。

会发生什么?

当块钩子 return 是一个字符值时,该值包含在输出中:

In knitr, hooks can also be used to insert texts into the output. To do this, the hook function must return a character result. [knitr: hooks]

在这种情况下,没有明确的 return 挂钩值。因此,if() 的 return 值是 returned。 if() 反过来 returns 的值就是 library returns:

if returns the value of the expression evaluated, or NULL invisibly if none was (which may happen if there is no else). [see ?"if"]

最后:

library returns (invisibly) the list of attached packages [see ?libray]

如何避免?

首先,例子不是很好。没有理由使用块挂钩加载包。如果需要 lattice,则应将其加载到 setup 块中。

但在某些情况下,类似的块挂钩 可能很有用。然后,解决方案是显式 return NULL:

knit_hooks$set(myPackage = function(before, options, envir){

    if(before) library(lattice)
    return(NULL)
  })