Maximilian
Maximilian

Reputation: 4229

Combine LaTeX with R markdown and pandoc

I have created a R markdown (RStudio) document and I would like to have that output in pdf combined with some part (i.e. first page) of my LaTeX document. So basically, I would like to do some bits with R Markdown (generating some R output) and write something down in LaTeX and have this two combined into 1 pdf document.

What would be the steps? Thx.

Upvotes: 3

Views: 2266

Answers (1)

Cedric
Cedric

Reputation: 2474

To demonstrate how to insert pdf pages using the pdfpages package, I first create a pdf file with four pages using the pdf() command.

The .Rnw (Knitr) script is as following

\documentclass[a4paper]{article}
\usepackage[final]{pdfpages}
\usepackage[pagestyles]{titlesec}
\usepackage{hyperref}
\title{An example on how to add external pdf pages}
\begin{document}
\maketitle
\tableofcontents
\section{First section}
\subsection{First subsection}
This is an empty section with a chunk to create one pdf with four pages

<<mtcarsplot, echo = TRUE, eval = TRUE,  fig.show='hide'>>=
library(knitr) 
pdf(file="figure/mtcarsplot.pdf",onefile=TRUE)
ggplot(mpg, aes(drv, model)) +
      geom_point() +
      facet_grid(manufacturer ~ ., scales = "free", space = "free") +
      theme(strip.text.y = element_text(angle = 0))
ggplot(mtcars, aes(wt, mpg))+ geom_point(aes(colour=factor(cyl), size = qsec))
ggplot(mpg, aes(x=factor(cyl), y=hwy, fill=factor(cyl)))+ geom_violin(scale = "width")
mosaicplot(Titanic, color = TRUE)
dev.off()
@

\phantomsection
\addcontentsline{toc}{subsection}{Second subsection (phantom)}
\includepdf[pages={1-2,{},4},nup=2x2]{figure/mtcarsplot.pdf}

\end{document}

To insert pages for the external document use

\includepdf[<key=val>]{<filename>}

The simplest will be \includepdf[pages=-] which will include all the pages from the document.

The code to include pages is

 \includepdf[pages={1-2,{},4}],nup=2x2]{figure/mtcarsplot.pdf}

{1-2,{},4} means that I included page 1 to 2, a blank page, then page 4.

The other command is nup=2x2 which has included four pages in two rows and two columns withing the same page.

It is often usefull to include external pdf as sections or subsections of the document created, this is done with :

\phantomsection
\addcontentsline{toc}{subsection}{Second subsection (phantom)}

The output shows the four pages in one page, with one left blank, and the table of contents with the phantom section.

pdfpage_example

Upvotes: 1

Related Questions