Skip to content

Instantly share code, notes, and snippets.

@egouldo
Last active August 29, 2015 14:26
Show Gist options
  • Save egouldo/53e72026590a312b9785 to your computer and use it in GitHub Desktop.
Save egouldo/53e72026590a312b9785 to your computer and use it in GitHub Desktop.
creates a latex fragment (as opposed to standalone latex document) from an Rmarkdown file. Useful for including knitted latex into a bigger latex document.
create_latex <- function(f){
knitr::knit(f, 'tmp-outputfile.md');
newname <- paste0(tools::file_path_sans_ext(f), ".tex")
mess <- paste('pandoc -f markdown -t latex -p -o', shQuote(newname),"tmp-outputfile.md")
system(mess)}
# The function above takes an `Rmd` file as its input, knits the file to `md`, and then converts it to `TeX` by calling pandoc from the command-line. The secret ingredient lies in the pandoc call... When knitting using Rstudio, Rstudio calls the pandoc standalone `-s` flag when it compiles the pdf. This generates a 'standalone' document, i.e. one that contains latex preamble. This is obviously necessary when you want to view the PDF, but is problematic when you want to generate a latex fragment only from Rmd.
# I instead sought to generate a latex 'fragment' from `Rmd` with knitr, that can be later incorporated into a main TeX file. So the solution was simply to create a pandoc command line call that omits the `-s` standalone flag. I achieved this by calling pandoc from R with `system()` inside the above function.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment