One of the other nice things that can be done with R Markdown is you can create ebooks. Ebooks can be created by creating separate RMakdown files for each chapter then knit them all together to generate the book.

Ebooks can be created in the following formats:

  • PDF (via LaTeX)
  • HTML (GitBook style, Bootstrap style or Tufte style)
  • EPub

rmb-book script

To get started with book down we actually have a new command to compile the book. Instead of calling render on a RMarkdown document like we have been previously we need to call render_book.

We can use the same docker image I introduced earlier in this tutorial but we will need to create a new script to call it.

Put the following into the rmb-book script and put it somewhere in your path (on my system its in ~/.local/bin) and call chmod +x rmd-book on it.

docpath=`realpath $1`
docker run --rm -v `pwd`:`pwd` --workdir `pwd` wiltaylor/rmarkdown:latest Rscript -e "require(bookdown); render_book('$docpath')"

First book

Now we have the script ready we can start on our book. First step is to create a new folder for your book and put a index.Rmd file in it.

title: Demo Book
author: Wil Taylor
output: bookdown::pdf_book

## Index.Rmd
This is some text in the index file.

Now to break this down:

  • title and author are what you expect the title of the book and who wrote it.
  • output - Like with regular R Markdown documents this controls the output file format. Unlike regular R Markdown though they have different values.
    • bookdown::gitbook - Generates html in a gitbook style.
    • bookdown::tufte - Html book in a Tufte style.
    • bookdown::pdf_book - Creates a pdf version of the book using LaTeX
    • bookdown::epub - Generates a epub version of the book


now we have the index.Rmd file created we can start working on chapters. The way chapters work is bookdown will import the index.Rmd file first and will then import all other Rmd files in the directory in alphabetical order. Because of this I suggest naming all your chapter files starting with the number of the chapter 01-foo.Rmd for example then 02-bar.Rmd. That way it will import them in the expected order.

More options

There are heaps of options and customizations you can make to your book. I suggest reading the bookdown documentation here.

RMarkdown Series