【问题标题】:Unwanted R code echo when compiling PDF with knitr使用 knitr 编译 PDF 时出现不需要的 R 代码回显
【发布时间】:2015-08-30 22:16:50
【问题描述】:

我有一个包含以下代码的 .Rnw 文件。运行knitr::knit() 一次,R 代码不会不回显。再次运行knitr::knit(),R 代码会在 PDF 中回显。为什么?如何防止 R 代码回显?

<<load_chapter_2, echo=FALSE, warning=FALSE, message=FALSE,cache=TRUE>>=

options(digits=2)

opts_chunk$set(eval=TRUE, results = "hide", echo=FALSE, warning=FALSE, message=FALSE, fig.height=5, fig.width=5, fig.pos="!ht", fig.align='center')

@


\documentclass[a4paper,11pt]{article}

\usepackage{lipsum} % Required to insert dummy text

% \usepackage{nameref} commented out as was causing extra \else error

\usepackage{graphicx}

\usepackage{placeins} % to control figure placement with \FloatBarrier

\usepackage{xspace}

\usepackage{caption}

\usepackage{subcaption}

\usepackage{array} % for line breaks in table

\usepackage[comma, sort&compress]{natbib} 
\setlength{\bibsep}{0pt plus 0.3ex}


\begin{document}
\title{}
\author{}
\date{\today}
\maketitle

\section{Header}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

<<plot_1>>=

plot(1)

@
\FloatBarrier


\end{document}

【问题讨论】:

    标签: r pdf latex knitr sweave


    【解决方案1】:

    你必须设置cache = F。我认为原因是cache = TRUE第二次将代码存储在内存中,而echo = F被忽略了。

    【讨论】:

      【解决方案2】:

      您不应该缓存您的设置块 - 这意味着您的 options 和 opts_chunk$set 将不会在后续调用 knit() 时运行。 cache = TRUE 应该用于产生结果的代码块,如果代码没有改变,结果也不会改变。但是,您还需要注意依赖关系。

      有关详细信息,请参阅http://yihui.name/knitr/demo/cache/。请特别查看标有“重要说明”的部分,其中包含以下内容:

      非常重要的是要注意,通常一个块有 不应缓存副作用。尽管 knitr 试图保留 print() 的副作用,还有其他副作用 没有保存。以下是一些您不能使用缓存的情况 块:

      1. 设置 R 选项,如 options('width') 或 pdf.options() 或 knitr 中的任何其他选项,如 opts_chunk$set()、opts_knit$set() 和 knit_hooks$set()
      2. 通过library()在缓存的块中加载包,这些包将被未缓存的块使用(完全可以加载 在缓存块中打包并仅在缓存块中使用它们,因为 knitr 保存缓存块的包列表,但未缓存 chunks 无法知道之前缓存中加载了哪些包 块)

      否则下一次chunk会被跳过,所有的设置都在 它将被忽略。对于这些,您必须明确使用 cache=FALSE 块。

      【讨论】:

      • 只是为了检查cache = TRUE可以在opts_chunk$set()里面使用吗?
      • @luciano 是的,但是设置选项等的任何其他块都需要明确的cache = FALSE
      猜你喜欢
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 2016-07-11
      • 2012-08-04
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      相关资源
      最近更新 更多