Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "Compile PDF" and knit2pdf

I have a .Rnw file that I am able to compile into a PDF using the "Compile PDF" button in RStudio (or Command+Shift+k). However, when I use knit2pdf the graphics are not created and the complete PDF is not created. Why would this happen? How do you specifically set where the images will be stored so that pdflatex can find them?

Here is an example. I am aware that this question that I posted a few days ago has a similar example, but in my mind these are two different questions.

This file will run just fine and produce a PDF if I hit "Compile". I don't get any errors, the figure is produced in the /figure directory, and all is well.

%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}

However, when I run this script that is intended to do exactly the same thing as hitting "Compile" (is it?) the figure is not created and I get the not-surprising error below about not being able to find it.

#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.

NOTE: If you are trying to reproduce this (and thanks!) then make sure you run the knit2pdf script FIRST to see that it doesn't create the figures. If you hit "Compile" first then the figures will be there for knit2pdf to use, but it will not accurately represent the situation.

like image 961
Nancy Avatar asked Oct 18 '22 22:10

Nancy


1 Answers

The solution: Make sure to set the working directory to the project directory before using knit2pdf, then shorten the "input" path to just the .Rnw file. Thus...

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

setwd("/Users/me/Desktop/thing")
knit2pdf(input = "test.Rnw", output = "test.tex")
like image 134
Nancy Avatar answered Oct 21 '22 17:10

Nancy