How to combine two RMarkdown (.Rmd) files into a single output? - r

I have two files in the same folder: chapter1.Rmd and chapter2.Rmd, with the following content:
chapter1.Rmd
---
title: "Chapter 1"
output: pdf_document
---
## This is chapter 1. {#Chapter1}
Next up: [chapter 2](#Chapter2)
chapter2.Rmd
---
title: "Chapter 2"
output: pdf_document
---
## This is chapter 2. {#Chapter2}
Previously: [chapter 1](#Chapter1)
How can I knit these so that they combine into a single pdf output?
Of course, render(input = "chapter1.Rmd", output_format = "pdf_document") works perfectly but render(input = "chapter1.Rmd", input = "chapter2.Rmd", output_format = "pdf_document") does not.
Why do I want to do this? To break up a giant document into logical files.
I've used #hadley 's bookdown package to build latex from .Rmd but this seems like overkill for this particular task. Is there a simple solution using knitr/pandoc/linux command line I'm missing? Thanks.

August, 2018 update: This answer was written before the advent of bookdown, which is a more powerful approach to writing Rmarkdown based books. Check out the minimal bookdown example in #Mikey-Harper's answer!
When I want to break a large report into separate Rmd, I usually create a parent Rmd and include the chapters as children. This approach is easy for new users to understand, and if you include a table of contents (toc), it is easy to navigate between chapters.
report.Rmd
---
title: My Report
output:
pdf_document:
toc: yes
---
```{r child = 'chapter1.Rmd'}
```
```{r child = 'chapter2.Rmd'}
```
chapter1.Rmd
# Chapter 1
This is chapter 1.
```{r}
1
```
chapter2.Rmd
# Chapter 2
This is chapter 2.
```{r}
2
```
Build
rmarkdown::render('report.Rmd')
Which produces:
And if you want a quick way to create the chunks for your child documents:
rmd <- list.files(pattern = '*.Rmd', recursive = T)
chunks <- paste0("```{r child = '", rmd, "'}\n```\n")
cat(chunks, sep = '\n')
# ```{r child = 'chapter1.Rmd'}
# ```
#
# ```{r child = 'chapter2.Rmd'}
# ```

I'd recommend that people use the bookdown package for creating reports from multiple R Markdown files. It adds a lot of useful features like cross-referencing which are very useful for longer documents.
Adapting the example from #Eric, here is a minimal example of the bookdown setup. The main detail is that the main file has to be called index.Rmd , and must include the additional YAML line site: bookdown::bookdown_site:
index.Rmd
---
title: "A Minimal bookdown document"
site: bookdown::bookdown_site
output:
bookdown::pdf_document2:
toc: yes
---
01-intro.Rmd:
# Chapter 1
This is chapter 1.
```{r}
1
```
02-intro.Rmd:
# Chapter 2
This is chapter 2.
```{r}
2
```
If we Knit the index.Rmd bookdown will merge all the files in the same directory in alphabetical order (this behaviour can be changed using an extra _bookdown.yml file).
Once you get comfortable with this basic setup, it is easy to customise the bookdown document and output formats using additional configuration files i.e. _bookdown.yml and _output.yml
Further Reading
R Markdown: The definitive Guide: Chapter 11 provides a great overview of bookdown
Authoring books with bookdown provides a comprehensive guide on bookdown, and recommended for more advanced details.

This worked for me:
Rmd_bind <-
function(dir = ".",
book_header = readLines(textConnection("---\ntitle: 'Title'\n---")))
{
old <- setwd(dir)
if(length(grep("book.Rmd", list.files())) > 0){
warning("book.Rmd already exists")
}
write(book_header, file = "book.Rmd", )
cfiles <- list.files(pattern = "*.Rmd", )
ttext <- NULL
for(i in 1:length(cfiles)){
text <- readLines(cfiles[i])
hspan <- grep("---", text)
text <- text[-c(hspan[1]:hspan[2])]
write(text, sep = "\n", file = "book.Rmd", append = T)
}
render("book.Rmd", output_format = "pdf_document")
setwd(old)
}
Imagine there's a better solution and would be nice to have something like this in rmarkdown or knitr packages.

Related

rmarkdown read code from file and display with highlight

I have two RMarkdown files. main.Rmd which is the main file which is rendered as well as example.Rmd which holds a longer example and is used elsewhere (hence it lives in its own document).
I want to include example.Rmd in the main.Rmd file with code highlighting of its RMarkdown code but the code of example.Rmd does not need to be executed, as if I set eval=FALSE and copied all code into the chunk by hand.
An example MWE is
main.Rmd
---
title: This is main.rmd
output: html_document
---
```{r}
# attempt that doesnt work
cat(readLines("example.Rmd"), sep = "\n")
```
and in example.Rmd
---
title: This is example.rmd
output: html_document
---
```{r}
# code that is not executed but shown in main.Rmd
data <- ...
```
Set eval=FALSE in the example.Rmd file and then include it in main.Rmd using child chunk option.
example.Rmd
---
title: This is example.Rmd
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(eval = FALSE)
```
```{r}
# This is from example.Rmd
x <- rnorm(10)
y <- rnorm(10)
lm(y ~ x)
```
```{r}
# some comments
print("This is from example.Rmd")
```
main.Rmd
---
title: This is main.Rmd
output:
html_document:
highlight: haddock
---
```{r example, child="example.Rmd"}
```
Edit
To show full source-code of the Rmarkdown file, one possible option could be reading that Rmd file and then cat it with chunk option comment="".
Now about the syntax highlighting; there's a chunk option class.output with which it is possible to specify a language name for which pandoc supports syntax highlighting.
You can get the list of language names for which pandoc has syntax highlighting support by running the following,
pandoc --list-highlight-languages
(Note, if you don't have pandoc installed separately, you can also use the pandoc installed with Rstudio itself. Run rmarkdown::pandoc_exec() to get the pandoc executable path)
Now, the file we are trying to include actually contains not just R code, but also markdown and yaml syntaxes. So it's a kind of mixed thing and pandoc has no syntax highlighting support out of the box for this. Still I have chosen c as syntax highlighting language just to show the possibility. (Also tried r, but syntax-highlighting is not so distinctive)
---
title: This is main.Rmd
output:
html_document:
highlight: tango
---
## Rmarkdown
```{r example, echo=FALSE, class.output="c", comment=""}
cat(readLines("example.Rmd"), sep = "\n")
```
But still if you want a specific syntax-highlighting for Rmarkdown, you can actually create one. See here from the pandoc documentation itself and also this answer on SO about this.

Run R markdown (.Rmd) from inside other R script to produce HTML

As the example, if you create a new R markdown file and save it as 'test'. Can one then run or deploy this test.Rmd file from within a normal R script. The purpose being to generate the output in HTML, without having to open the .Rmd file.
I'm hoping to create one master file to do this for many markdown files in one go; which would save considerable time as you then don't have to open many markdown files and wait for each one to complete.
You are looking for rmarkdown::render().
Contents of "test.Rmd"
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
Contents of script.R
# provided test.Rmd is in the working directory
rmarkdown::render("test.Rmd")
A Way to Render Multiple Rmd
cwd_rmd_files <- list.files(pattern = ".Rmd$")
lapply(cwd_rmd_files, rmarkdown::render)
Thanks the-mad-statter, your answer was very helpful. The issue I faced, required me to prepare markdown dynamically. By adapting your code, that's easily possible:
Contents of "test_dyn.rmd"
---
title: "Untitled"
output: html_document
---
The chunk below adds formatted text, based on your inputs.
```{r text, echo=FALSE, results="asis"}
cat(text)
```
The chunk below uses your input in as code.
```{r results}
y
```
Contents of "script_dyn.r"
in_text <- c("**Test 1**", "*Test 2*")
in_y <- 1:2
lapply(1:2, function(x) {
text <- in_text[[x]]
y <- in_y[[x]]
rmarkdown::render(input = "test_dyn.rmd", output_file = paste0("test", x))
})
Like this you can create files with different text and different variables values in your code.

Split rmarkdown presentation code over multiple text files [duplicate]

I have two files in the same folder: chapter1.Rmd and chapter2.Rmd, with the following content:
chapter1.Rmd
---
title: "Chapter 1"
output: pdf_document
---
## This is chapter 1. {#Chapter1}
Next up: [chapter 2](#Chapter2)
chapter2.Rmd
---
title: "Chapter 2"
output: pdf_document
---
## This is chapter 2. {#Chapter2}
Previously: [chapter 1](#Chapter1)
How can I knit these so that they combine into a single pdf output?
Of course, render(input = "chapter1.Rmd", output_format = "pdf_document") works perfectly but render(input = "chapter1.Rmd", input = "chapter2.Rmd", output_format = "pdf_document") does not.
Why do I want to do this? To break up a giant document into logical files.
I've used #hadley 's bookdown package to build latex from .Rmd but this seems like overkill for this particular task. Is there a simple solution using knitr/pandoc/linux command line I'm missing? Thanks.
August, 2018 update: This answer was written before the advent of bookdown, which is a more powerful approach to writing Rmarkdown based books. Check out the minimal bookdown example in #Mikey-Harper's answer!
When I want to break a large report into separate Rmd, I usually create a parent Rmd and include the chapters as children. This approach is easy for new users to understand, and if you include a table of contents (toc), it is easy to navigate between chapters.
report.Rmd
---
title: My Report
output:
pdf_document:
toc: yes
---
```{r child = 'chapter1.Rmd'}
```
```{r child = 'chapter2.Rmd'}
```
chapter1.Rmd
# Chapter 1
This is chapter 1.
```{r}
1
```
chapter2.Rmd
# Chapter 2
This is chapter 2.
```{r}
2
```
Build
rmarkdown::render('report.Rmd')
Which produces:
And if you want a quick way to create the chunks for your child documents:
rmd <- list.files(pattern = '*.Rmd', recursive = T)
chunks <- paste0("```{r child = '", rmd, "'}\n```\n")
cat(chunks, sep = '\n')
# ```{r child = 'chapter1.Rmd'}
# ```
#
# ```{r child = 'chapter2.Rmd'}
# ```
I'd recommend that people use the bookdown package for creating reports from multiple R Markdown files. It adds a lot of useful features like cross-referencing which are very useful for longer documents.
Adapting the example from #Eric, here is a minimal example of the bookdown setup. The main detail is that the main file has to be called index.Rmd , and must include the additional YAML line site: bookdown::bookdown_site:
index.Rmd
---
title: "A Minimal bookdown document"
site: bookdown::bookdown_site
output:
bookdown::pdf_document2:
toc: yes
---
01-intro.Rmd:
# Chapter 1
This is chapter 1.
```{r}
1
```
02-intro.Rmd:
# Chapter 2
This is chapter 2.
```{r}
2
```
If we Knit the index.Rmd bookdown will merge all the files in the same directory in alphabetical order (this behaviour can be changed using an extra _bookdown.yml file).
Once you get comfortable with this basic setup, it is easy to customise the bookdown document and output formats using additional configuration files i.e. _bookdown.yml and _output.yml
Further Reading
R Markdown: The definitive Guide: Chapter 11 provides a great overview of bookdown
Authoring books with bookdown provides a comprehensive guide on bookdown, and recommended for more advanced details.
This worked for me:
Rmd_bind <-
function(dir = ".",
book_header = readLines(textConnection("---\ntitle: 'Title'\n---")))
{
old <- setwd(dir)
if(length(grep("book.Rmd", list.files())) > 0){
warning("book.Rmd already exists")
}
write(book_header, file = "book.Rmd", )
cfiles <- list.files(pattern = "*.Rmd", )
ttext <- NULL
for(i in 1:length(cfiles)){
text <- readLines(cfiles[i])
hspan <- grep("---", text)
text <- text[-c(hspan[1]:hspan[2])]
write(text, sep = "\n", file = "book.Rmd", append = T)
}
render("book.Rmd", output_format = "pdf_document")
setwd(old)
}
Imagine there's a better solution and would be nice to have something like this in rmarkdown or knitr packages.

Company logo in PDF output only on the first page

I was wondering if there is a way to include the company logo to a PDF document created by R Markdown only on the first page of the document. I have searched for an answer and the closest I could find is this. There are multiple solutions presented in the answers, however, neither of them works for me because they either:
include the logo at every page of the document (not just first); or
include the chapter title in the header (and a horizontal line below it) along with the logo.
I am looking for a way to include just the plain logo, with no chapter titles only on the first page of a PDF R Markdown document and I've ran out of all the resources I could find online. Is there someone who could aid me?
Before anyone asks: yes, it strictly has to be a PDF document, not HTML.
The \includegraphics code line is insert after the R SETUP chunk in markdown.
Here is an example of where I put the line \includegraphics :
---
geometry: "margin=1.5cm"
classoption: landscape
output:
pdf_document: # Export to pdf
number_sections: yes
includes:
in_header: ltx.sty
---
```{r SETUP, include=FALSE, message=FALSE, warning=FALSE}
knitr::opts_chunk$set(echo = FALSE,
warning = FALSE,
message = FALSE,
results = "asis")
library(knitr)
library(kableExtra)
library(some_packages)
options(scipen = 999,
digits = 2,
width = 110)
```
\definecolor{astral}{RGB}{87,146,204}
\allsectionsfont{\color{astral}}
\setcounter{tocdepth}{5}
<!-- Title page -->
\includegraphics[width=7cm]{logo.jpg}
\begin{center}\begin{Large}
Project 1
\end{Large}\end{center}
\vfill
# Some R chunk
```{r results='asis'}
# Table, code, graphics.
```
So the line is insert between the R SETUP chunk and the next R chunk.

R Markdown automatically makes title

I'm about to write my master's thesis in R Markdown and when I knit to pdf there is the standard title which one gets in LaTeX with '\maketitle'.
The autor, the title and the name. Quite ugly.
I don't know how to delete that ...
Thank you!
Overview
You can modify your YAML header in many ways. Please read the PDF Documents section within RStudio's RMarkdown page.
Reproducible Example
When you first create an .rmd file, this is the default YAML header:
---
title: "Default_YAML"
author: "Daffy Duck"
date: "2/17/2018"
output: pdf_document
---
# Header
Some text.
```{r}
df <- read.csv( file = "somefilepath.csv" )
```
You can customize what does and does not appear within your YAML header. Below is an example of me deleting the entire thing:
# Header
Some text.
```{r}
df <- read.csv( file = "somefilepath.csv" )
```

Resources