2015-06-15 44 views
0

我有一個.Rnw文件,其中包含下面的代碼。運行knitr::knit()一次,並且R代碼不會回顯。第二次運行knitr::knit(),R代碼在PDF中回顯。爲什麼?我如何防止R代碼回顯?用knitr編譯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} 

回答

3

您不應該緩存您的設置塊 - 這意味着您的optionsopts_chunk$set將不會在隨後的knit()調用中運行。 cache = TRUE應該用於產生結果的代碼塊,如果代碼沒有改變,結果也不會改變。但是,您還需要小心依賴關係。

查看http://yihui.name/knitr/demo/cache/瞭解更多詳情。看看特別是在標有「重要事項」部分已執行以下操作:

需要注意的是,通常有 副作用不應該被緩存塊這是非常重要的。儘管knitr試圖保留print()的 副作用,但仍有其他副作用 未保留。這裏有一些情況下,你不能使用緩存的 塊:

  1. 通過library()設置R選項,如options('width')pdf.options()或類似opts_chunk$set()opts_knit$set()knit_hooks$set()
  2. 裝載包knitr任何其他選項中緩存塊,這些包將由未緩存的塊使用(將緩衝塊加載 包並僅在緩存塊中使用它們是完全正確的,因爲 knitr保存緩存塊的包列表,但未緩存 塊無法知道這個^ h包在以前的緩存 塊裝)

否則下一次塊將被跳過,並在 所有設置將被忽略。你必須明確地使用cache=FALSE這些 塊。

+0

這是完全正確的。 –

+0

只需檢查'cache = TRUE'是否可以在'opts_chunk $ set()'中使用? – luciano

+0

@luciano是的,但隨後任何設置選項等的塊都需要顯式的'cache = FALSE' –

2

您必須設置cache = F。我認爲原因是cache = TRUE代碼第二次存儲在內存中,echo = F被忽略。