我正在扩展我最近在此发布的问题(Put figure directly into Knitr document (without saving file of it in folder))。
我正在编写一个R包,为输出数据摘要的用户生成.pdf文件。我在包中有一个.Rnw脚本(这里,我的MWE称为test.Rnw)。用户可以这样做:
1) knit("test.Rnw") to create a test.tex file
2) "pdflatex test.tex" to create the test.pdf summary output file.
.Rnw文件生成许多图像。最初,这些都保存在当前目录中。这些图像被保存到目录中(或者在.tex文件上调用pdflatex时创建的.aux或.log文件)看起来并不像它一样整洁(因为用户必须记得删除这些图像文件) 。其次,我还担心当脚本多次运行时,这种不整洁可能会导致问题。
因此,在我之前的帖子中,我们通过将图像保存到临时文件夹来改进.Rnw文件。我被告知每次打开一个新的R会话时,临时文件夹中的文件都会被删除。但是,我仍然担心某些事情:
1)我觉得我可能需要插入一行,如第19行所示:
system(sprintf("%s", paste0("rm -r ", temppath, "/*")))
每次运行.Rnw文件时自动删除临时文件夹中的文件(这样每次重新启动R时都不会删除图像)。这将使当前目录保持图像清洁,并且用户不必记住手动删除图像。但是,我不知道这个"解决方案"将通过CRAN标准有一行删除临时文件夹中的文件。原因是它删除了用户系统中的文件,如果其他程序将文件写入临时文件夹,则可能会导致问题。我觉得我已经读过有关CRAN的信息,因为显而易见的原因,不允许从用户的计算机上写/删除文件。 CRAN对这种做法有多严格?有没有一种安全的方法呢?
2)如果在临时文件中写入和删除图像文件不起作用,那么实现相同效果的另一种方法是什么(运行脚本而不会在文件夹中创建繁琐的图像文件)?是否可以将图像直接嵌入输出文件中(不需要保存到任何目录)?我很确定这是不可能的。但是,我被告知可以使用.Rmd这样做,并且我可以将.Rnw转换为.Rmd。这可能很困难,因为.Rnw文件必须遵循某些格式(文本和边距)才能获得正确的输出,并且它非常长。是否可以仅对生成图像的块使用.Rmd功能(将图像直接插入输出),而不重写整个.Rnw文件?
以下是我的MWE:
\documentclass[nohyper]{tufte-handout}
\usepackage{tabularx}
\usepackage{longtable}
\setcaptionfont{% changes caption font characteristics
\normalfont\footnotesize
\color{black}% <-- set color here
}
\begin{document}
<<setup, echo=FALSE>>=
library(knitr)
library(xtable)
library(ggplot2)
# Specify directory for figure output in a temporary directory
temppath <- tempdir()
# Erase all files in this temp directory first?
#system(sprintf("%s", paste0("rm -r ", temppath, "/*")))
opts_chunk$set(fig.path = temppath)
@
<<diamondData, echo=FALSE, fig.env = "marginfigure", out.width="0.95\\linewidth", fig.cap = "The diamond dataset has varibles depth and price.",fig.lp="mar:">>=
print(qplot(depth,price,data=diamonds))
@
<<echo=FALSE,results='asis'>>=
myDF <- data.frame(a = rnorm(1:10), b = letters[1:10])
print(xtable(myDF, caption= 'This data frame shows ten random variables from the distribution and a corresponding letter', label='tab:dataFrame'), floating = FALSE, tabular.environment = "longtable", include.rownames=FALSE)
@
Figure \ref{mar:diamondData} shows the diamonds data set, with the
variables price and depth.Table \ref{tab:dataFrame} shows letters a through j
corresponding to a random variable from a normal distribution.
\end{document}