"Compile PDF" 和 knit2pdf 之间的区别

Difference between "Compile PDF" and knit2pdf

我有一个 .Rnw 文件,我可以使用 RStudio 中的 "Compile PDF" 按钮(或 Command+Shift+k)将其编译成 PDF。 但是,当我使用 knit2pdf 时,没有创建图形,也没有创建完整的 PDF。为什么会这样?你如何具体设置图像的存储位置以便pdflatex可以找到它们?

这是一个例子。我知道我几天前发布的 问题有一个类似的例子,但在我看来,这是两个不同的问题。

如果我点击 "Compile",此文件将 运行 正常并生成 PDF。我没有收到任何错误,图形是在 /figure 目录中生成的,一切都很好。

%test.Rnw
\documentclass{article}
\usepackage[margin=.5in, landscape]{geometry}
\begin{document}

This is some test text!

<<setup, include=FALSE, results='hide', cache=FALSE>>=
opts_chunk$set(echo=FALSE, warning = FALSE, message = FALSE,
 cache = FALSE, error = FALSE)
library(ggplot2)
@

<<printplotscreen, results='asis'>>=
ggplot(diamonds) + 
  geom_bar(aes(x = color, stat = "bin"))
@

\end{document}

但是,当我运行这个脚本的目的是做与命中"Compile"完全相同的事情时(是吗?)数字是未创建,我在下面收到有关无法找到它的不足为奇的错误。

#test.R
library("knitr")

knit2pdf(input = "~/Desktop/thing/test.Rnw",
         output=paste0('~/Desktop/thing/test','.tex'))

Error in texi2dvi(file = file, pdf = TRUE, clean = clean, quiet = quiet,  : 
  Running 'texi2dvi' on 'test.tex' failed.
LaTeX errors:
! LaTeX Error: File `figure/printplotscreen-1' not found.

注意:如果您要重现此内容(谢谢!),请确保您首先 运行 knit2pdf 脚本以确保它不会创建图形。如果您先点击 "Compile",那么 knit2pdf 可以使用这些数字,但它不会准确地表示情况。

解决方法:确保在使用knit2pdf之前将工作目录设置为项目目录,然后将"input"路径缩短为.Rnw文件。因此...

test.R
library("knitr")
diamonds = diamonds[diamonds$cut != "Very Good",]

setwd("/Users/me/Desktop/thing")
knit2pdf(input = "test.Rnw", output = "test.tex")

这里有一些关于这个问题的参考资料:
Changing working directory will impact the location of output #38 ; make sure the output dir is correct (#38) 似乎在使用 knit2pdf() 时,它会自动将输出文件设置为输入文件所在的目录。作者不建议我们在项目中间更改工作目录。

所以我目前的解决方案是将工作目录保存为旧目录(getwd()),将工作目录更改为要保存输出文件的位置,使用knit2pdf()输出文件,最后把工作目录改成原来的目录。