RStudio Community question about generating tex file

Han Oostdijk

2020/04/24

Date last run: 24Apr2020

Question

In the RStudio Community website the question was asked how to produce from an Rmd source only the part of the tex file (without preamble) that inserts a plot. The asker wanted to include that part in another tex file with its own preamble. My solution to generate a pdf and tex file and manually copy the relevant part of the tex file would obviously not work in an automated workflow. While I was thinking how to solve this with an adapted pandoc file, Kieran Healy provided an easier solution. They do however not create exactly the same output.

The sample Rmd file with my solution (use adapted template)

Rmd file:

---
graphics: yes
output: 
  pdf_document: 
    keep_tex: true
    template: awellis_template.tex 
---
`​``{r sinus-plot, echo=FALSE, fig.cap='My nice sinus plot'}
plot(sin(seq(-pi, pi, length.out = 100)))
`​``

template file awellis_template.tex :

$body$
resulting awellis.tex (Han’s method)
\begin{figure}
\centering
\includegraphics{awellis_files/figure-latex/sinus-plot-1.pdf}
\caption{My nice sinus plot}
\end{figure}

A problem with this method is that pandoc produces error messages such as

Error: LaTeX failed to compile awellis.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips.

The reason is of course that the template does not produce the necessary parts for a complete LaTeX document.

Kieran’s solution (use separate knit and pandoc)

We use the same input but remove the template file from the yaml.

knitr::knit("awellis_without_template.Rmd") 

rmarkdown::pandoc_convert("awellis_without_template.md", to = "latex", output = "awellis.tex")
resulting awellis.tex (Kieran’s method)
\begin{figure}
\centering
\includegraphics{figure/sinus-plot-1.png}
\caption{My nice sinus plot}
\end{figure}

Comparison

Comparing the two methods:

So choose Kieran’s method unless you really need a pdf file as intermediate graphics file.

Session Info

This document was produced on 24Apr2020 with the following R environment:

  #> R version 3.6.0 (2019-04-26)
  #> Platform: x86_64-w64-mingw32/x64 (64-bit)
  #> Running under: Windows 10 x64 (build 18363)
  #> 
  #> Matrix products: default
  #> 
  #> locale:
  #> [1] LC_COLLATE=English_United States.1252 
  #> [2] LC_CTYPE=English_United States.1252   
  #> [3] LC_MONETARY=English_United States.1252
  #> [4] LC_NUMERIC=C                          
  #> [5] LC_TIME=English_United States.1252    
  #> 
  #> attached base packages:
  #> [1] stats     graphics  grDevices utils     datasets  methods   base     
  #> 
  #> loaded via a namespace (and not attached):
  #>  [1] compiler_3.6.0 magrittr_1.5   tools_3.6.0    glue_1.4.0     stringi_1.4.6 
  #>  [6] knitr_1.28     stringr_1.4.0  xfun_0.10      rlang_0.4.5    evaluate_0.14 
  #> [11] purrr_0.3.3