"编译PDF"之间的区别和knit2pdf

时间:2015-11-05 21:20:50

标签: r latex pdf-generation knitr pdflatex

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

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

如果我点击"编译"此文件将运行正常并生成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}

然而,当我运行这个脚本时,它的目的与命中&#34;编译&#34;完全相同。 (是吗?)这个数字没有创建,我在下面找不到令人惊讶的错误,因为无法找到它。

#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脚本以确定它没有创建数字。如果你点击&#34;编译&#34;首先,数字将在那里使用knit2pdf,但它不能准确地表示情况。

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:0)

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

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

相关问题