This project was inspired by the bookdown package and is an updated version of my Senior Thesis template in the reedtemplates package here . It was originally designed to only work with the Reed College LaTeX template, but has since been adapted to work with many different institutions by many different individuals. Check out the Customizing thesisdown to your institution section below for examples.

Currently, the PDF and gitbook versions are fully-functional. The word and epub versions are developmental, have no templates behind them, and are essentially calls to the appropriate functions in bookdown.

If you are new to working with bookdown / rmarkdown , please read over the documentation available in the gitbook template at https://ismayc.github.io/thesisdown_book .

The current output for the four versions is here:

  • PDF (Generating LaTeX file is available here with other files in the book directory .)

Under the hood, the Reed College LaTeX template is used to ensure that documents conform precisely to submission standards. At the same time, composition and formatting can be done using lightweight markdown syntax, and R code and its output can be seamlessly included using rmarkdown .

Customizing thesisdown to your institution

In an ideal world, this package would support a variety of different LaTeX templates from a wide range of institutions and we’d love to get it there at some point. Until that time, realize that this was designed to only work with the Reed College LaTeX template but others have adapted it to work with their institutions. Here are some that have customized it to fit their needs. It is recommended you review how they changed the files by comparing their repositories to this one and then make tweaks to yours as needed. Feel free to file an issue on this repo if you have questions/troubles.

Have you created a thesisdown template for your institution and would like to have it included here? Make a PR similar to the commit done to include jayhawkdown . I’ll review it and merge it in. Let’s keep the list going!

Using thesisdown from Chester’s GitHub

Special thanks to Ben Marwick for helping to add a lot more clarity to the directions below from the README of his spin-off huskydown package .

Using {thesisdown} has some prerequisites which are described below. To compile PDF documents using R , you are going to need to have LaTeX installed. By far the easiest way to install LaTeX on any platform is with the tinytex R package:

You may need to install a few extra LaTeX packages on your first attempt to knit as well. Here is one such example of how to do so:

To use {thesisdown} from RStudio :

Ensure that you have already installed LaTeX and the fonts described above, and are using the latest version of RStudio . You can use thesisdown without RStudio. For example, you can write the Rmd files in your favorite text editor (e.g.  Atom , Notepad++ ). But RStudio is probably the easiest tool for writing both R code and text in your thesis. It also provides a nice way to build your thesis while editing. We’ll proceed assuming that you have decided to use the RStudio workflow.

Install the {bookdown} and {thesisdown} packages. Note that {thesisdown} is not available on CRAN at the moment and that’s why install.packages("thesisdown") won’t work. Use remotes::install_github() as shown below instead to install the package.

          Note that you may need to restart RStudio at this point for the following dialog to show up.

  • Get started with the {thesisdown} template. There are two options for doing so.

3a) RECOMMENDED Create a new RStudio project with a {thesisdown} template.

In RStudio, click on File > New Project > New Directory . Then select Thesis Project using thesisdown from the dropdown that will look something like the image below. You’ll see the graduation cap as the icon on the left for the appropriate project type.

writing thesis in r markdown

Next, give your project a name and specify where you’d like the files to appear. In the screenshot below, the project name is my_thesis and it will appear as a new folder on my Desktop.

writing thesis in r markdown

If you got this far, skip over step 3b which is the older version of getting the template. It might force you to change some of the directories to get knitting to work and has some other limitations as well. That’s why step 3a is recommended.

3b) Use the New R Markdown dialog to select Thesis :

writing thesis in r markdown

Note that this will currently only Knit if you name the directory index as shown above. This guarantees that index.html is generated correctly for the Gitbook version of the thesis.

  • After choosing which type of output you’d like in the YAML at the top of index.Rmd , Knit the index.Rmd file to get the book in PDF or HTML formats.

Day-to-day writing of your thesis

You need to edit the individual chapter R Markdown files to write your thesis. It’s recommended that you version control your thesis using GitHub if possible. RStudio can also easily sync up with GitHub to make the process easier. While writing, you should git commit your work frequently, after every major activity on your thesis. For example, every few paragraphs or section of text, and after major step of analysis development. You should git push at the end of each work session before you leave your computer or change tasks. For a gentle, novice-friendly guide to getting starting with using Git with R and RStudio, see https://happygitwithr.com/ .

To render your thesis into a PDF, open index.Rmd in RStudio and then click the “knit” button. To change the output formats between PDF, gitbook and Word, look at the output: field in index.Rmd and comment-out the formats you don’t want.

The PDF file of your thesis will be deposited in the _book/ directory, by default.

The following components are ones you should edit to customize your thesis:

_bookdown.yml

This is the main configuration file for your thesis. You can change the name of your outputted file here for your thesis and other options about your thesis here.

This file contains all the meta information that goes at the beginning of your document. You’ll need to edit the top portion of this file (the YAML) to put your name on the first page, the title of your thesis, etc. Note that you need to have at least one chapter start in the index.Rmd file for the build to work. For the template, this is done with # Introduction in the example from the template.

01-chap1.Rmd , 02-chap2.Rmd , etc.

These are the Rmd files for each chapter in your dissertation. Write your thesis in these. If you’re writing in RStudio, you may find the wordcount addin useful for getting word counts and readability statistics in R Markdown documents.

Store your bibliography (as bibtex files) here. We recommend using the citr addin and Zotero to efficiently manage and insert citations.

Specific style files for bibliographies should be stored here. A good source for citation styles is https://github.com/citation-style-language/styles#readme .

figure/ and data/

Store your figures and data here and reference them in your R Markdown files. See the bookdown book for details on cross-referencing items using R Markdown.

  • Full license
  • MIT + file LICENSE
  • Chester Ismay Maintainer, author
  • Nick Solomon Author

Any fool can know. The point is to understand. - Einstein

Tyson S. Barrett, PhD

#rstats Enthusiast, Data Scientist

© 2024. All rights reserved.

Writing Your Dissertation (or Thesis) in RMarkdown

A few days ago I announced that I had completed the requirements for a PhD in Quantitative Psychology and (maybe more interestingly) that I had written my entire dissertation in Rmarkdown. It was more of a shoutout to @RStudio but the interest in how I did it was exciting.

I defended my dissertation and now have a PhD 🤓 Excited to have that over with. My entire dissertation was written in \#rstats with \#rmarkdown and got many compliments about the look of the manuscript - grateful to @rstudio for providing those incredible tools — Tyson Barrett (@healthandstats) February 10, 2018

Several indicated that they’d like to see the process I went through to do this. Questions included:

  • How I used RMarkdown for the writing,
  • How I formatted it to match the University’s formatting standards, and
  • How I worked with my PI while writing with RMarkdown.

I want to answer each of these questions.

Writing with RMarkdown

First, I want to talk about how I went about writing a dissertation in RMarkdown. With the advent of bookdown , a number of people asked if that was the tool I used to write my dissertation. Although it is a fantastic tool that I have used elsewhere , I wanted the flexibility of using pure RMarkdown. What I mean by that is that I needed to be able to integrate Latex formatting files within the system without having to learn the ins-and-outs of bookdown .

The files I’ll highlight throughout this post can be found at osf.io/753kc . The first, and most important file, is the only file you’ll knit. It is the main .Rmd file, in my case, called MarginalMediation.Rmd . The header YAML in this file looks like this:

Most of it contains pieces that, if you’ve used somewhat more advanced RMarkdown, you are probably familiar with. These include the title, author, output, bibliography, and nocite. The documentation for this can be found at RMarkdown’s website . The other pieces are more rare but still documented as useful YAML options in RMarkdown. Among these, documentclass: DissertateUSU is important. This pulls information from another file called DissertateUSU.cls , which ultimately controls much of the formatting of the outputted PDF file. This file was made particularly to match the specified formatting for Utah State University (thus the dissertateUSU name) and thus won’t be a perfect fit for all the other universities. My guess is that it is a great starting point for you to match your own situation’s guidelines.

This file has comments throughout to highlight what each section is doing. It includes the formatting of the title page as well. Using the Params: section of the YAML, the title page is populated with the information put there. It does this as, while knitting, a file called preamble.tex is written through a function that is found early in the RMarkdown file. This function comes through the dissertateUSU R package on GitHub (download with devtools::install_github("tysonstanley/dissertateUSU" )). After installing the package, I recommend using the template to get going using the approach shown below.

writing thesis in r markdown

This provides a starting template for the main .Rmd file. It doesn’t include the R chunks but you can easily add those. It will look something like that below (minus the R chunks but I recommend, as I said before, adding them).

writing thesis in r markdown

For those familiar with RMarkdown, this starting R chunk (the only one present in the template) is important for the remainder of the file. There’s a warning ## Do NOT Remove above the dissertateUSU::preamble_for_title() function. That is the function that takes the information from the Params: , places them in a preamble.tex file that fills in the title page information.

In the preceding image, you may have noticed the use of the R chunk option: child = 'abstract.Rmd' . This means it takes the abstract.Rmd file in the same directory and knits in within the main .Rmd file. That is, the abstract file that I wrote in a separate RMarkdown file, will appear within the main output with the formatting provided in the main .Rmd file.

This general appraoch of using the child = option allows you to write each chapter within its own .Rmd file (without worrying too much about formatting). This allows editing and error finding to go much more smoothly. You’ll see in the OSF repository that I have my files for all my chapters and the different front matter (abstracts, dedication, acknowledgement, etc.). These are very simple .Rmd files.

This is how the majority of the writing went. I added the writing and other information, including R code (which is printed in the appendices). However, the References, the appendices and the CV at the end of the document took a little bit of hacking to make it work right.

writing thesis in r markdown

This “hack” required using <div id="refs"></div> (line 205 in the image) to force the references to be printed before the appendices and CV. Further, the appendix files essentially grab the code used in the manuscript and, using echo=TRUE in the R chunks, prints them nicely.

For the references, I used a BibTex file, in this case called Diss.bib . I used Mendeley as my references manager and then exported all of my references to the .bib file. This allowed me to use the regular RMarkdown citing while using csl: ref_format.csl (note that it is CSL and not CLS that is used for the formatting) to format the references correctly (in my case APA style). This file was downloaded from the vast repository of csl files . I looked for the one that fit what I was looking for, downloaded it, and named it ref_format.csl and put it in my dissertation’s directory.

I’m hoping between this post and the OSF repository, this provides you with the information to start writing and formatting your dissertation within RMarkdown.

Other Things

  • For spell checking, I used the built in spell check in RStudio. It wasn’t perfect but worked really well.
  • For version control, I used the Open Science Framework (OSF; where I have the files linked). I would have used Git and GitHub had there been collaborators that knew how to use it. This worked well as it provides a simplified version control system while providing tools to share it later.
  • I used some simulations in my dissertation. I used a regular script file to write these and run them (using the terminal when possible). I pasted this code within the manuscript toward the end of the writing (when I knew the simulations were done). This allowed me to include them in the appendices more easily.

As a final note, I recommend using RStudio Projects as well. These help keep things more organized, especially when it comes to saving and reading in different files.

Formatting the PDF

Formatting took a lot of Latex code that, honestly, I googled. It provided guidance on how to make small changes to the overall formatting. The vast majority of the formatting took place in the DissertateUSU.cls with a little happening in the main .Rmd file.

I don’t have time to go into detail here as most formatting is based on Latex. Many universities have latex style files that you can use, which can save you loads of work as the formatting will be done for you in large measure.

Working with a Non-useR PI

This may have been the most challenging part of the process. If you have a PI that knows markdown or Latex, then you should be good to go with editing and updating the document using any number of version control systems (like Git with GitHub.com ). However, a vast number of senior researchers do not use these, generally using Microsoft’s Word.

This is how my situation was. My PI at first wanted Word documents that she could edit using “track changes.” But I convinced her that, given my desire to have a reproducible workflow and use R throughout all my analyses, this was an appropriate strategy to avoid inputting mistakes. It took some convincing but I outlined the errors that I was going to avoid using this system:

  • My tables would be made automatically and, with minor updating, would be publication ready. No manual input of the numbers in the table can not only save my time but my PI’s time checking the table for little errors. Thus, if my analyses were correct, so were my tables.
  • My figures would auto update. If I made a change or fixed an error, I didn’t have to go update it in the manuscript. Instead, it was automatically updated in the manuscript itself.
  • The manuscript, in general, looks more professional than those produced by Word. The formatting feels sharper, the figures are auto-fitted on the page (as a floating object), and the table and figure auto-numbering is easy to use and hard to mess up (in contrast to Word which I always struggle not messing up). In addition, the formatting is more predictable using this approach than through Word (e.g., Word tables can randomly go all crazy, leaving cells out or combining them without you asking).

These plus other R related benefits (free, open-source, the helpful community, etc.) helped me win her over to this approach (and the fact that she is a very reasonable researcher that I’ve enjoyed working with).

With this, we agreed that I would produce the PDF files that she could mark up and return to me with comments.

Notably, another approach we almost took on (that I think works well too), is to produce the Word documents without too much formatting using the .Rmd files. Then, after the initial round of edits (so that from there, there would be fewer edits), use the well formatted PDF files for her to see the look of the pages and make smaller edits and comments.

Overall, this is probably the biggest hang up for most individuals that are interested in using RMarkdown with a PI that doesn’t use Markdown, Latex or R.

Conclusions

This was a quick introduction to how I wrote my dissertation using RMarkdown. I hope it was helpful to at least get started on the road to using RMarkdown for your own scientific writing. Please leave feedback if you have time!

Related Posts

`dtplyr` and `tidyfast` are teaming up (well, at least in this blog post) 03 dec 2019, six things i learned while making `tidyfast` 13 nov 2019, guest post: interpreting interactions in multilevel models 29 oct 2019.

Writing a Master’s thesis with R Markdown and Bookdown

I wrote my Master’s thesis with bookdown. This post contains some tips to modify the layout and other stuff.

I finished my Master’s thesis very recently, and I wrote it with R Markdown, and more precisely with the bookdown package. It was really comfortable to do absolutely everything with R: data treatment, use of econometric methods, redaction with chunk of codes, and even the slides for the presentation! However, I have also spent a non-negligible part of my time trying to have a correct layout, essentially for the first pages. I found that some things were not as easy to do as they should be. This post contains some solutions to these problems.

Why bookdown ?

A small preamble before starting to list these problems and solutions: why did I use bookdown and not rmarkdown ? bookdown has a few advantages that are very important when writing a Master’s thesis (or an academic paper in general), such as cross-references between sections, figures, tables, etc. See the bookdown book for all the details.

While it is possible to create a bookdown project with RStudio, I “manually” made my own, because I have the impression there are a lot of files created automatically by RStudio that would just confuse myself. Therefore, I had a file containing the YAML and the chunks necessary to load all the packages needed and to run the child documents. Child documents are .Rmd files that contain only some Markdown text and code chunks (no YAML). They make it much easier to write a thesis since it is possible to divide it in several pieces (introduction, literature review, method, etc.).

In addition to Global.Rmd (which contains YAML and setup chunks), I used two .tex files: preamble.tex is where I put all the LaTeX commands and packages I used, and titlepage.tex to make my custom titlepage, acknowledgments and abstract before the table of contents.

LaTeX packages and commands

In preamble.tex , I put all the LaTeX commands, many of them being \usepackage . For example, the R package kableExtra provides a list of LaTeX packages required to be able to customize the tables (see here ).

Here’s a small list of the commands I used for my thesis.

\renewcommand{\baselinestretch}{1.3} to change the space between lines;

\pagenumbering{gobble} to remove page numbering for the first pages, that contain the title, the table of content (TOC), the lists of figures and tables (LOF and LOT) and some blank pages. I used \pagenumbering{arabic} after the YAML to start the page numbering at the right place.

\usepackage{caption} ; \captionsetup[table]{name=Tableau} ; \captionsetup[figure]{name=Figure} . These three commands (to put on three separate lines) are here to change the name of tables and figures. If you’re writing in English, you probably won’t need them, but they were necessary to write in French.

the following lines create a new command to create a blank page after the titlepage. Strangely, \pagebreak or \newpage didn’t work inside the titlepage and I had to find an alternative:

\usepackage{afterpage} \newcommand\blankpage{% \null \thispagestyle{empty}% \addtocounter{page}{-1}% \newpage}

Titlepage, acknowledgements and abstract

Concerning these three components, I put them in another file named titlepage.tex . This is the layout I wanted:

a titlepage with some logos and some information on my thesis and my university;

a blank page;

acknowledgements on a new page;

abstract on a new page;

TOC, LOF and LOT on a new page.

To do so, I started the titlepage with \begin{titlepage} and customized it as I wanted. But before putting \end{titlepage} , I placed \afterpage{\blankpage} , which is the command we define in preamble.tex . With this, I had a titlepage and a blank page.

The next step was to create two pages containing the acknowledgements and the abstract This was easily done in LaTeX, and this time I could use \pagebreak at the end of the acknowledgements to create a new page for the abstract. I also put another \pagebreak to finish titlepage.tex , so that TOC, LOF and LOT (created in the YAML) could start on a new page.

Include LaTeX files in YAML

As explained, I had two .tex files to run when compiling the R Markdown file:

preamble.tex is a list of commands that should be placed before \begin{document} when this .Rmd file will be converted to .tex . Therefore, I used in_header in the YAML to compile it.

titlepage.tex contains some elements that should be in the final PDF document. Since this should appear first (before the rest of the .Rmd document), I used before_body in the YAML.

Here are examples of the three files: Global.Rmd , preamble.tex and titlepage.tex .

--- output: bookdown::pdf_book: includes: in_header: preamble.tex before_body: titlepage.tex keep_tex: true toc: yes toc_depth: 3 indent: true link-citations: yes lot: true lof: true --- <!-- Start the redaction on a new page --> \newpage <!-- Start page numbering where the redaction starts --> \pagenumbering{arabic} ```{r globaloptions, include=FALSE} # Include here chunk options ``` ```{r packages} # Load here the packages ``` <!-- Call the child documents --> ```{r body, child = c('01-Intro.Rmd', '02-Literature.Rmd', '03-Data-and-method.Rmd', '04-Results.Rmd', '05-Discussion.Rmd', '06-Conclusion.Rmd')} ``` <!-- Placement of bibliography --> # References {-} <div id="refs"></div> <!-- Place the appendix after the bibliography --> ```{r appendix, child = c('07--Appendix.Rmd')} ```

% Line spacing \renewcommand{\baselinestretch}{1.3} % Page number and chapter at the top of the page \pagestyle{headings} % Important packages \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage[dvipsnames]{xcolor} \usepackage{hyperref} \usepackage{dcolumn} \usepackage{booktabs} \usepackage{longtable} % Figure and table names \usepackage{caption} \captionsetup[table]{name=Tableau} \captionsetup[figure]{name=Figure} % Packages for kableExtra \usepackage{array} \usepackage{multirow} \usepackage{wrapfig} \usepackage{colortbl} \usepackage{pdflscape} \usepackage{float} \usepackage{tabu} \usepackage{threeparttable} \usepackage{threeparttablex} \usepackage[normalem]{ulem} \usepackage{makecell} % Remove page numbering before start of redaction \pagenumbering{gobble} % Command to make a blank page \usepackage{afterpage} \newcommand\blankpage{% \null \thispagestyle{empty}% \addtocounter{page}{-1}% \newpage}

\begin{titlepage} \centering Title of my thesis \afterpage{\blankpage} \end{titlepage} \section*{Acknowledgements} Thanks everyone \pagebreak \begin{center} \textbf{Abstract} \end{center} Bla bla bla... \pagebreak

Hope this helps!

Corrections

If you see mistakes or want to suggest changes, please create an issue on the source repository.

Text and figures are licensed under Creative Commons Attribution CC BY 4.0 . Source code is available at https://github.com/etiennebacher/personal_website_distill , unless otherwise noted. The figures that have been reused from other sources don't fall under this license and can be recognized by a note in their caption: "Figure from ...".

For attribution, please cite this work as

BibTeX citation

Website created with the R package distill .

Write your dissertation in Rmarkdown

Using rmarkdown to create complex pdf documents.

Created by Anna

Tutorial Aims

  • Understanding the advantages of using Rmarkdown for writing pdf documents, focusing on writing your dissertation;
  • Learning how to create the template for the main page, and appending all the other sections to it;
  • Using LaTex for embellishing the pdf output and functioning as a supplement to Markdown;
  • Becoming familiar with knitr and kableExtra packages.
  • Introduction
  • The front page
  • The abstract
  • Table Of Contents (TOC)

Bibliography and citations

  • The appendix
  • Let’s merge!

1. Introduction.

This tutorial is a step-by-step guide on creating a complex pdf document, including text, figures, references, images, formatting, and more, all using Rmarkdown.

If you are new to Rmarkdown, you might find our other Rmarkdown tutorial useful to do first. Click on Getting Started with R Markdown to open the tutorial.

All the resources for this tutorial, including data, images, and some example Rmarkdown files, can be downloaded from this repository . Download by clicking on Code -> Download ZIP, then unzipping the archive in a folder you will use for this tutorial.

To do the tutorial, you will need to have R (tutorial was tested on R 4.0.4), RStudio, and a LaTeX distribution. You can easily install TinyTex by running two lines in the R console.

TinyTex is a custom LaTex distribution based on TeX Live, relatively small in size.

There are several other distributions that you install on your local machine, including MikTex , MacTex and TeX Live , but TinyTex works best for R users, as with it you don’t have to install LaTex packages which you don’t need, and missing packages will be automatically installed on RStudio. Also, TinyTex does not require sysadmin privileges.

To install or uninstall TinyTex from your local machine, this code is necessary (which you can write in your RStudio console).

Once the distribution is installed, you can move on to the next section.

2. The “main” Rmarkdown document.

When you write a document, whether it’s an essay, or a scientific report, or your undergraduate dissertation, it is going to be structured in different sections.

In the scientific world, these sections consist of: an introduction, methods, results, discussion, and bibliography. If we consider a published paper or a thesis, these also contain an abstract, perhaps a section with abbreviations, and at the end present a section with supplementary information or an appendix.

As the aim of this tutorial is to successfully write your dissertation with Rmarkdown, it is useful to consider the number of sections necessary for your output and to avoid writing everything in one single .Rmd document .

In fact, for sake of easier read and better organisation, but also faster upload of the final pdf, we are going to create multiple .Rmd files, corresponding to the main sections of the dissertation. We are then going to merge them, within the “mother” document.

First thing we are going to do is create the main.Rmd file (you can name the file like this if you wish).

Here, we are going to set the first page of your dissertation and we are going to link all the other .Rmd documents containing the different sections. In this file, we are also going to set the general formatting rules (written in LaTex ), which are going to apply to the entire document.

All the files that you need to complete this tutorial can be downloaded from this GitHub repository link . Clone and download the repo as a zip file, then unzip it.

Open Rstudio and create a new .Rmd file, within the repo folder you’ve just downloaded , by clicking on the blank sheet with the green plus one on the left-hand side of the interface.

open_md

Once you have created a new Rmarkdown document, leave the title and author blank (you don’t want these to appear at the top of your pdf) and select PDF as the Default Output Format. Click OK and let’s start writing in the new file.

opening_md

You will see at the top a section called YAML header , delimited by three hyphens (—). The header embeds the information that you have just given (blank for the title, no author and pdf_document as your desired output), and allows you to set the “rules” that are going to be applied throughout the document (as well as the linked documents). The information you are going to insert here defines the metadata of your document: its content will affect the code, content and the rendering process of the document, but itself will not show in the output.** Check out the Rmarkdown Cookbook on YAML metadata , if you wish to find out more. This link offers you an exhaustive field guide of possible YAML arguments - check it out to have a better understanding of the kinds of metadata you can input in your document.

Each university or publishing institution will have their own formatting rules , which you’ll need to follow when structuring and writing your work.

For this tutorial, we are going to follow the guidelines from the School of GeoSciences (University of Edinburgh) . These are as of 2020 - if they have changed edit them accordingly, or, if you are writing for another institution, edit them according to its specific guidelines.

NOTE. If you are writing for an institution other than university, perhaps you are publishing your dissertation on a scientific journal, you need to look for their “Author’s Information” page as you can download their own templates . Here is an example of the template provided by Nature .

We need to add more details and specifications to our YAML header to apply to the entire to document (and its ‘child’ documents).

  • number_sections: TRUE will automatically create sections in your Table Of Contents (TOC), ordered according to the type of header you specify (main, sub-, subsub- etc.);
  • geometry : sets margin sides for pdf output (according to School of Geosciences guidelines);
  • fontsize : sets the entire font throughout the document to be 11 pt. You can change that in the file for specific sections of your choosing;
  • header-includes : allows you to specify all the LaTex packages you are going to need in your file. In this way, you can keep all the specifics inside your main .Rmd document and they will apply to the child documents, too .

The packages include:

  • float : improves the interface for defining floating objects , like figures and tables;
  • sectsty : helps you change the style of any or all LaTex sectional headers in the article, book or report classes. Examples include the addition of rules above or below a section title;
  • paralist : provides enumerate and itemise environments that can be used within paragraphs to format the items as either running text or as separate paragraphs with preceding number or symbol ;
  • setspace : provides support for setting spacing between lines in a document. Options include \singlespacing, \onehalfspacing and \doublespacing commands (which we’ll see below). As you can see, I’ve already set the general rule to be 1.5 spacing (as per university guidelines);
  • fancyhdr : the package provides extensive facilities, both for constructing headers and footers and for controlling their use ;
  • lastpage : references the number of pages in your LaTex document through the introduction of a new label;
  • dcolumn : makes use of the “array” package to define a “D” column for use in tabular environments;
  • natbib : provides flexible biography support , including both author-year and numbered references, both in-text and long-format. From the package, I have also specified the bibliographic style to be agsm , which corresponds to Harvard . You can specify whatever style you desire, have a look at the styles available in the package here ;
  • tocbibind : automatically adds the bibliography and/or index and/or the contents, etc., to the Table Of Contents (TOC) listing . The options nottoc disables the inclusion of the toc (which otherwise would be a duplicate), and numbib makes the bibliograpgy numbered in the toc list, thus consistent with the other section titles.

The YAML also needs to specify the file containing all of your references, with the .bib extension. In our case, I have already created a file called bibliography.bib , containing a few references on the Atlantic Puffin ( Fratercula arctica ), subject of our sample dataset for this tutorial (which we are going to work within the appendix section ). Check out the bibliograpgies and citations section from the Rmarkdown Cookbook , if you’d like to dive deeper into the topic.

Erase all the content from the RMarkdown document, but the first code chunk, and write the following after the first code chunk.

The \allsectionsfont command specifies changes to your header font - in this case, to have them centred. Instead, we have specified \subsectionfont and \subsubsectionfont (for sub-headers) to be ragged right.

\pagenumbering{gobble} , instead, does not print any page number , and this is ideal for the moment, as we are about to create the front page, which does not require one. Remember though, the gobble option in the pagenumbering command has the side effect to reset the page number to 1 - so it is unlikely to be helpful other than at the beginning of your document!

a) The front page

Let’s create the front page of the dissertation. It’s an important one, as it’s going to make the first great impression of your work!

The front page requires all elements to be centred . We are going to start using some LaTex syntax to do so. Write the following at the end of what we’ve written so far (below the first code chunk and the settings on text alignment).

This is written in LaTex. We are defining a space in the document, within which anything we will write will be centred on the page.

To be clearer, the content of the front page is all inside the begin and end centring commands. The \begin{centering} has to be at the top and \end{centering} needs to be at the bottom in the the front page .

In between the \begin{centring} and \end{centring} we are going to specify a 3 cm spacing from the top of the page, to then insert the first element: the university logo.

Undearneath the vertical spacing (vspace) function, add a new code chunk by selecting on the icon “insert” and clicking on “R”.

uni_logo_chunk

Inside it, write

This way, the image of the UoE logo is going to appear at the top of the page.

Knitr is the most important package used in Rmarkdown, to help you create elegant, flexible and fast report generation. If you click on the Knit button on the top of the page, you are able to repeatedly output your pdf so that you can constantly check to see how your formatting has changed as you continue working on your Rmarkdown file!

As you can see, I have named the code chunk “uni_logo”, making it easier to retrieve the chunk later on, when there are going to be many more.

Echo = False will only show the output of the code inside the code chunk, not the code itself.

Out.width is a feature for images and figures, in particular the percentage width that the image will occupy out of the total white space in the pdf document.

You can retrieve the image of the university logo with the function include_graphics() .

1 cm distant from the logo, we need to add the name of the university and that of your department, As an example:

You recall the \vspace function from above. \Large sets all text below it to be of larger font, and \bf which sets the text within curly brackets to bold .

\Large is a font changing command, and the pt size it reflects is often determined by the document class itself. Here is an overview of the values for the standard classes.

It’s time to add the title of your dissertation! I have written mine below just as an example.

As you might have figured, adding \doublespacing will double the space between lines of text. By wrapping a specific part of your text within curly brackets and adding the function \bf at the start, you will specify that only that part of the text will need to be in bold.

This link explains in more detail the different ways to do simple text formatting .

The university guidelines specify to have the title all capitalised . And finally, the \\ sign will break the text onto a new line (just like \n for a string in R code!).

To finish up the front page we need to add the author, degree and date!

Again, as a matter of formatting guidance, I added some specified spacing in between the lines of text that follow the thesis title.

Remember that rmarkdown will remember any input you last gave it, and to change it again need to specify the new function for the lines of text that follow!

In fact, by changing the font back to \normalsize you input the .Rmd file to go back to a ‘normal’ font (12 pt), since the last input you gave it was to be \Large .

Now that we have created the front page, you can knit the document by clicking on the Knit button at the top of the RStudio interface, to check out the output!

If you’re interested, check out the chapter what happens when we render from Rmarkdown Cookbook , to find out about the workflow from .Rmd to .pdf (or another output format).

knit_button

Don’t worry if it takes time at first for the document to knit - it is normal at first and particularly if the document is heavy!

Also, knitting can be quite buggy at first. That is also normal as you need to get used to some common practices to write in markdown that would avoid unnecessary problems.

A few ways to avoid debugging :

  • develop chunks and execute them until they work, before moving on to creating new ones;
  • knit the document regularly to check for errors;

If there is an error, check out this webpage describing common problems with rmarkdown (and some solutions) .

Once you’ve successfully knitted your document, the front page should look like this.

front_output

In case the front page isn’t exactly as the image above, I have reported the summary of the code that should be written so far in your .Rmd (YAML included) .

b) Abstract

We can add the Abstract on a new page , by specifying this LaTex command. Remember to start writing outside of the centering command from now on.

Anything you’ll write or insert after this command will appear on a new page. This way you have control over the distribution of your content.

You remember the pagenumbering command from before. It does not let any page number to be displayed in the pdf output.

In the new page, write the following:

The title “Abstract” is centered and bold, while the spacing between lines of text is set to 1.5.

abstract

I have included main guidelines for writing an abstract, which should come useful to you when writing it.

abstract_output

3. Table Of Contents (TOC).

One very important section is the TOC. It is typically located after the abstract (and abbreviations section, which is optional, but very useful ).

Below, I have specified the syntax for including the toc, which is very straightforward. Paste it below the abstract.

I have included the roman option in the pagenumbering command, telling the document that from now on, it can start numbering the pages, roman way.

The remaining syntax prepares a new page for writing the toc - it is created automatically, and will identify headers and subheaders according to how you have written them (see markdown syntax for headers and subheaders).

You should get a new page with Contents as title and the rest is blank - for now. This page is going to get populated from now on, as you’ll be adding headers and subheaders.

toc_empty

4. “Child” documents.

Looking good!

The front page of the dissertation is ready, and so are your abstract and toc.

Now we need to add the different sections of your dissertation, which we’ll create on separate .Rmd files as I mentioned at the beginning of this tutorial. These .rmd files will behave as ‘children’ to the main file, which we have worked on so far.

In the main document, paste the following after the toc section you created just above.

As you can see, we’ve just added a code chunk for each section of your dissertation. The “child” feature specified in the code chunk options, links the content of this other .Rmd file to the main one. This means that once you’ll knit the main document, the content from each of the child documents will be pasted and merged into one, final pdf .

Also, note that from the introduction onwards I’ve changed the pagenumbering to Arabic. You are going to see that in your pdf, the main sections are going to be numbered in Arabic, compared to the introductory pages (abstract, toc, acknowledgements), which are numbered in roman.

However, remember to make sure you’ve created all .Rmd files that you have specified in your main file and check the spelling ! As you can imagine, non-existing or misspelt files which you will try to link to the main document will result in an error, whenever you will try to knit to pdf.

To speed things up a little, I have created the files already and you can see them in the repository . Knitting the document now, you should see how the content from each has been pasted into one main document.

md_childdocs

You should now have a 10-page document, with each section of the dissertation appearing on a new page. The structure is coming along nicely! Well done!

For any scientific report and article, citing your sources and creating a list of references at the end of your document is fundamental if not mandatory.

We are going to do the same for our template.

When creating and managing a bibliography in LaTex, we use the package natbib for customising citations, when using BibiTex . BibiTex is a tool and file format used to describe and process lists of references, mostly in conjunction with LaTex documents.

There are a series of reference managers freely available to download, which ease and speed up the amount of time you are going to spend referencing and citing in your work.

The most popular and best ones (to my advice) are Mendeley and Zotero . One of the nice features about them is that after saving your list of references in a folder, you can export them into BibiTex format ( .bib ). This way, you can directly link the content from the new .bib file to any document that supports LaTex syntax.

Recall the packages dedicated to adding a bibliography in the YAML header ( natbib and tocbibind ), and the specification of the .bib file containing your bibliography.

If you open bibliography.bib , each citation is structured as such:

You can see the citation starts with an @ , followed by curly brackets, which contain the citation key , and other information relevant to the article (such as title, abstract, author, date etc.).

The citation key is fundamental for in-line referencing . Keep that in mind!

Try to write a few in-line citations in any section of the dissertation that you’d like. For example, open the introduction.Rmd file and paste the following.

The citation key is always referred to within curly brackets, and you can specify multiple citations within the same brackets. The command changes the type of in-line citation. Observe the result to see what each command returns specifically.

intext_citation

In case you have more doubts and want to find out more about commands for citing and other commands and options from the natbib package, check out this reference sheet .

Last, we need to write our list of long references. Our bibliography.Rmd does not have a title when you first open it. Don’t worry about it, as the \bibliography command takes care of adding a title itself.

Open the bibliography.Rmd file and paste this simple command.

Note that the name of the file containing our list of references has to be included without the .bib extension in the \bibliography command. This command takes the whole content from the list and turns it into the Harvard long-format style of referencing. In alphabetical order, of course.

This is your output in the bibliography section.

biblio_long

And check out the table of contents, with the bibliography being included and numbered (thanks to numbib option in the tocbibbind package).

addedbiblio_toc

Finally, here are useful links from the Rmarkdown Cookbook on generating R package citations and cross-referencing within documents , which are not covered in this tutorial.

The appendix.

As an example of a child document, we are going to structure a section that we do not often work with, because it is optional, albeit very useful - the appendix. You might decide to include it or not in your final dissertation, but what you’re going to learn from now on applies to any section of your document.

However, some general rules apply to the appendix section. Appendices:

  • Appear the end of the document, often after references;
  • You should create one appendix for each topic, e.g. additional tables, additional figures, code, etc. Each should start on a new page;
  • If there are multiple appendices in your document, there should be labelled with letters, and usually accompanied by a title that clarifies their content;
  • Appendices are also included in the table of contents at the beginning of the main document.

We are going to follow these formatting rules and we are going to explore three types of appendices: additional tables, additional figures and code (used for programming during your research).

Opening the appendix.Rmd document, you will see it already contains some text I had added.

We will start with Appendix A: additional tables .

We are going to add a new chunk with the following code, to start coding live within the .Rmd.

We are opening a .csv file containing information on the Atlantic puffins ( Fratercula arctica ) species trend and temperature information from 1979 until 2008, in Norway.

Note: include=F in the {} makes sure that neither code chunk nor output is shown in the pdf output.

If you have never used the tidyverse package before don’t worry - it is not part of the learning objectives for this tutorial. If you want to learn about the Tidyverse, do this Coding Club tutorial .

Now, the data set is almost presentable and ready to be inserted into a table. There are still other details, like the number of decimals to be fixed, that knitr::kable() function helps to fix.

kableExtra is a package that uses kable() and pipes from the Tidyverse package, to build complex and professional tables. We are going to use one example for the sake of this tutorial, but if you wish to explore further on the large variety of features that kableExtra can offer, have a look at its manual . Moreover, kableExtra is often combined with viridisLite package, for using smoother colour scales .

Copy the following code chunk and run it (make sure it is spaced from the one above).

You can notice that the table has now appeared after the chunk and in the ‘Viewer’ tab on the bottom-right panel.

appendixA_table

REMEMBER: the output of the table in Rstudio Viewer is in HTML format. This means that on pdf will have a slightly different look, particularly when it comes to colours chosen. Make sure you specify these colours and check the output (kableExtra was initially made for HTML, not pdf outputs).

Moving on to Appendix B: additional figures . We are going to use the same data on the Atlantic Puffins.

As we did for the table, we could output our figure by coding directly inside the code chunk, and specifying include = F in the code chunk options, to only display the figure and not the code that generated it, in the pdf.

Otherwise, the knitr package provides us with options to add pre-saved figures. We’ve already used this function when adding the university logo to our main page.

As an example, we are displaying the mean temperature change between 1979 and 2008 in Norway.

  • fig.align defines the alignment of figures in the output;
  • fig.cap adds the figure caption at the bottom;
  • The list.files() function lists the files present in a specified path. Here I chose the ‘appendix_fig’ folder, where all the figures to insert in the appendix had been saved;
  • The 'include_graphics() function is part of the ‘knitr’ package, and it allows to embed external images in document format supported by ‘knitr’.

appendixB_fig

Finally, Appendix C: code . Let’s imagine we want to use our last appendix to include all the code we used to carry out our data cleaning, the statistical analyses, the features used for creating our figures and tables, and perhaps the custom functions we created to automate our work.

Remember that making the code available in the appendix favours the transparency and replicability of your work .

Doing this requires a very simple, single line of code.

As you can see, we are leaving the code chunk empty, and writing exclusively within the curly brackets, to set the options for display.

The function all_labels() from knitr returns a vector of all chunk labels in the document you’re working on (in this case, the appendix itself). The function thus retrieves all the source code chunks to this particular code chunk. Echo = True will show the source code inside this code chunk, which is equivalent to the source code from the entire document . Eval = False will not evaluate the code chunk as all the code has been executed before.

A list of code lines should appear within the code chunk and it corresponds to the code we have just written in the appendix.Rmd!

By code chunk label we mean the custom names that you can give the code chunk, to be differentiated from the others so you can more easily recognise it and its source code. Not only that, considering that all_labels() takes all labels and so all code chunks, it might be useful to exclude some which are not going to be necessary, like the setup label present at the top of your main.Rmd.

To avoid it, it will be necessary to add this new code chunk to above the all_labels() one.

Here you can see how it’s written in Rstudio…

appendixC_code

…and this is what it looks like when you knit the pdf!

appendixC_code_output

5. Let’s Merge!

Make sure that all the text we’ve written so far is spelt correctly , and be ready to knit the main document !

Now you can fill the sections in with your own content and your personal touch.

In the meantime, this is what your output should look like at the end of this tutorial.

6. Final tips.

Here are some final tips which I found to be essential when I wrote my dissertation on Rmarkdown.

  • I have not talked about it in detail in this tutorial, but the Abbreviations section (it comes after the TOC and acknowledgements ) can be very useful in your dissertation if you need to talk about many variables and features and need a way to speed things up (and save word count);
  • I also have not talked about this topic in this tutorial, but writing mathematical formulas or equations can be an important part of your work, especially when you are writing a dissertation that has a scientific purpose! If you need to write mathematical formulas or equations , I suggest you check out this link on math expressions and this one on markdown extensions to support math equations . Here is a list of LaTex mathematical symbols for you to explore, and here is a link to convert models to general equations ;
  • Make sure you have TinyTex installed to be able to create pdf documents from rmarkdown . Without it, it just won’t work. Remember that TinyTex is sufficient and is the best distribution for us R users;
  • NEVER write your content directly onto Rmarkdown! As much as it might seem faster, Rmarkdown does not provide a spell checker by default, and you might take longer than expected in ultimating and finalising your drafts. Plan the structure, the code that you want to include, the layout of each section to be written on Rmd , but always have the text saved and written on a word document first. It is much easier and quicker to paste in your content, once you’re 100% sure it is ready for submission;
  • Before knitting the main document, have a look at it, once, twice, three, four times… and more! This document will present many sections, and the smallest spelling mistake might crash your whole work. Since it’s going to be a large document, knit it a few times, only when necessary, and definitely when you’re sure to be printing your final pdf;
  • Don’t submit last minute!!! This rule would apply to any submission scenario. However, take your time to check for errors and debugging, if need be. You don’t want to find yourself at the end with errors that won’t allow you to knit your pdf and submit your work on time.

You can check out my dissertation written in Rmarkdown by clicking here .

Thank you for following this tutorial, I hope it has helped you with creating a nice and professional template for writing your work. Good luck with your submission and congratulations for completing your studies!

  • Install TinyTex
  • The Rmarkdown Cookbook
  • Rmarkdown cheetsheet
  • Pdf document (Rmarkdown)
  • The YAML Fieldguide
  • LaTex syntax
  • Html syntax
  • Knitr package
  • kableExtra package
  • ViridisLite package

Stay up to date and learn about our newest resources by following us on Twitter !

Contact us with any questions on [email protected], related tutorials:.

  • Getting Started with R Markdown
  • Intro to Github for version control
  • Coding etiquette
  • Setting up a GitHub repository for your lab
  • Transferring quantitative skills among scientists
  • Writing R packages in Rstudio

oxforddown : An Oxford University Thesis Template for R Markdown

Introduction.

Welcome to oxforddown ( Lyngs, 2019 ) , a thesis template for R Markdown that I created when writing my own PhD thesis at the University of Oxford. This template allows you to write in R Markdown, while formatting the PDF output with the beautiful and time-tested OxThesis LaTeX template . The sample content is partly adapted from thesisdown .

Hopefully, writing your thesis in R Markdown will provide a nicer interface to the OxThesis template if you haven’t used TeX or LaTeX before. More importantly, R Markdown allows you to embed chunks of code within your thesis and generate plots and tables directly from the underlying data, avoiding copy-paste steps. This gets you into the habit of doing reproducible research, which will benefit you long-term as a researcher, and also help anyone that is trying to reproduce or build upon your results down the road.

Why use it?

R Markdown creates a simple and straightforward way to interface with the beauty of LaTeX. Packages have been written in R to work directly with LaTeX to produce nicely formatting tables and paragraphs. In addition to creating a user friendly interface to LaTeX, R Markdown allows you to read in your data, analyze it and to visualize it using R , Python or other languages, and provide documentation and commentary on the results of your project. Further, it allows for results of code output to be passed inline to the commentary of your results. You’ll see more on this later, focusing on R . If you are more into Python or something else, you can still use R Markdown - see ‘Other language engines’ in Yihui Xie’s R Markdown: The Definitive Guide .

Using LaTeX together with Markdown is more consistent than the output of a word processor, much less prone to corruption or crashing, and the resulting file is smaller than a Word file. While you may never have had problems using Word in the past, your thesis is likely going to be about twice as large and complex as anything you’ve written before, taxing Word’s capabilities.

Who should use it?

Anyone who needs to use data analysis, math, tables, a lot of figures, complex cross-references, or who just cares about reproducibility in research can benefit from using R Markdown . If you are working in ‘softer’ fields, the user-friendly nature of the Markdown syntax and its ability to keep track of and easily include figures, automatically generate a table of contents, index, references, table of figures, etc. should still make it of great benefit to your thesis project.

Writing your manuscript in R Markdown

I really don’t like the Microsoft Office Suite. With the exception of PowerPoint (which I can almost always get to do what I want), the remainder of the suite, especially Word and Excel (NO, THAT COLUMN IS NOT A DATE, and even if it is, DO NOT REFORMAT IT), can be quite frustrating to work with.

For the last 6-7 years, I was beholden to doing most of my writing inside the Microsoft environment. While it got the job done, necessary tasks for scientific manuscripts (e.g., inserting citations and building bibliographies) were time consuming and cumbersome. Once I started getting more savvy in R and started using Markdown to keep a daily log/journal of my programming, I pillaged the web for ways to write inside an R environment to help streamline my workflow - keeping all of my code, data, figures, and writing in the same space. So far, it has worked great for me, and I was able to write my PhD dissertation and two published manuscripts using RMarkdown. This post is a sort of distillation of what I have learned, and what my workflow currently looks like.

Keep in mind, it works for me , but it may not work for you. You’ll have to try it out and see what does!

Additionally, folks are free to use the RMarkdown manuscript template that I have created for their own use.

Why RMarkdown?

The more and more I needed to write, the more and more I would get frustrated with Word. Pagination. Inserting figures. Dealing with formatting. When presented with a “page layout” view that I think most of us love, it’s easy to get lost in how your writing “looks” rather than what you are writing. This is particularly true for me as I tend to enjoy visual art/design quite a bit.

Writing in Markdown changed all of that. The ability to write in your text editor of choice strips away all of the nonsense of formatting and lets you deal with how your work looks on the backend. Editors such as Atom have “Zen” plugins that hide all the crap you don’t need to see (Git panes, project folders) and let you focus on what you need to get out of your head.

By far the greatest advantage to using a markdown-based writing workflow is dealing with references. Provided you have a well-curated citation manager (Zotero, Papers, Mendeley), providing in-text citations is incredibly easy, and compiling your formatted reference list involves writing literally 12 characters.

As far as why to chose RMarkdown, R and RStudio have all of the tools and packages you need to make the setup and transition to writing in markdown easy.

The workflow

Every time I start a new project in R, I do so in a skeleton directory that contains standardized folders to keep my business organized. An ongoing project looks something like this:

This directory structure lets me keep all things pertinent to a project in a single folder. Important to us right now, is the folders ms_body . Here, I keep all writing files (e.g., manuscript_draft.Rmd ) and manuscript figures that get inserted into my Rmd documents.

Generally, the process of writing a manuscript is pretty straight forward. Once you have drafts completed, you are able to compile your RMarkdown document (called “knitting” using the R package knitr ) into a PDF, Word file, or HTML.

Formatting your RMarkdown manuscript

I won’t go into too much detail of how to format your writing using Markdown, but rest assured it’s extremely easy. Check out the following:

https://rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdf

First, create your manuscript RMarkdown document in your R project by selecting “File -> New File -> RMarkdown.” Before you edit anything, save it immediately to your manuscripts folder, whatever that may be called (in my case, ms_body ). You can enter a file title and your name as the author, and select PDF as the default output format. Don’t worry, all of this can be changed later.

When you create this, the first thing that pops up is a RMarkdown template file:

rmarkdown_template

This file shows you generally how you can structure an RMarkdown file. We can get rid of all of this except the top portion that is delimited by three dashes (—). This section is called the YAML (Yet another markup language) header.

What’s in your YAML?

Generally, the YAML header contains a bunch of settings to help control how your finished product is rendered, where your bibliography file lives, what citation style you’re using, etc., etc. Below is the header from one of my current manuscripts.

In this, I am telling R a bunch of information including:

  • Title : what the manuscript title is
  • Author : Who wrote the damn thing
  • Output : in what format the rendered RMarkdown file is rendered. You can also include template Word files to tell R how you want your document rendered if you choose to export it into Word format.
  • fontfamily : what font I am using
  • fontsize : you guessed it, font size!
  • geometry : formatting of the page itself, in this case the margins
  • header-includes : these are a bunch of LaTeX libraries that I tell R to use to help format various aspects of the paper. For a basic RMarkdown manuscript, this can be ignored. I’m just really picky.
  • keywords : if your template uses them, keywords for the manuscript
  • bibliography : this one is important, and it tells R where your bibliography file, called a bibtex file, lives in your project. In this case, I am telling it to look in the current folder (the “./”) for a file called library.bib .
  • link-citations :
  • csl : this is also important. It is the path to the file that specifies which citation style you wish to use. You can download these from: https://www.zotero.org/styles
  • abstract here’s our first bit of writing! An option the YAML gives you is to include your abstract here. It isn’t necessary, you could simply include it as part of your RMarkdown text, but here it is, block indented following a bar ("|") to tell R that it’s one paragraph.

To start off, I would suggest making your YAML simple and including just the title, authors, output (use a simple output: pdf ).

After you get your YAML constructed, it’s time to get writing! There are many ways to format different manuscript sections, etc., I stick to using headings which in Markdown look like this:

Renders to…

Introduction

Subsection level 1, subsection level 2, subsection level 3.

This is typically where Microsoft Word underperforms the most when writing. Fortunately, it is super easy to provide citations writing in Markdown using BibTeX.

Most citation managers organize a BibTeX file for your library and store it along with your PDFs. This file contains all of the necessary information for building a citation in a standardized fashion. Each item in a BibTeX library contains a citation key; essentially a short code that you can insert into your writing to tell R when to include a particular citation formatted to your choosing when you knit your document. This key is what you’ll need to find. It’s usually automatically generated and stored within the paper metadata in your reference manager.

For example, my short codes contain the authors last name and date of publication (e.g., Hemberger.2020 ). When writing, you can insert these citations by first inserting an @ symbol, and placing them into square brackets for end-of-sentence citations (e.g., [@Hemberger.2020] ). You can also use them in context by simply using the @ symbol. (e.g., “ @Hemberger.2020 found that…”).

To include all of your citations as a formatted reference section, you need simply write # References as a section of your paper. R (and some LaTeX on the backend) will automatically collect your references and place them there in your format of choosing (the .csl file you specified in your YAML header).

The best part about this is when you inevitably get rejected from your first journal of choice, reformatting your references is as simple as downloading the appropriate .csl file and changing the citation style specification in your YAML.

Inserting images

Inserting figures is also super easy. To do so, use the following markdown code:

I typically write my figure captions using standard markdown formatting below the image. Additionally, I usually wrap my images with \newpage and \clearpage , which is some LaTeX that creates page breaks around my images/captions so they each live on their own page. I also will use a width parameter to control the rough size of the image on the page. Usually, I keep it at 100% of the width so the figure is as big as possible. Altogether, an figure and caption in my RMarkdown document will look like this:

Knitting your document

Once you are ready to compile your markdown code into your output of choice, you need simply click the “knit” button in the code pane and wait for the magic to happen. Any errors will be visible in the R Markdown tab in your console pane (including missing references, LaTeX errors, etc.).

This project is inspired by the {bookdown} and {thesisdown} packages, adapted to provide a template for writing a McMaster graduate thesis in R markdown.

The PDF uses McMaster Graduate Thesis LaTeX template.

Under the hood, the McMaster Graduate Thesis LaTeX template is used to ensure that documents conform precisely to submission standards. At the same time, composition and formatting can be done using lightweight {markdown} syntax, and R code and its output can be seamlessly included using {rmarkdown} .

Using {macdown}

Using {macdown} has some prerequisites which are described below. To compile PDF documents using R , you are going to need to have LaTeX installed. By far the easiest way to install LaTeX on any platform is with the {tinytex} R package:

You may need to install a few extra LaTeX packages on your first attempt to knit as well. Here is one such example of how to do so:

To use {macdown} from RStudio :

Ensure that you have already installed LaTeX and the fonts described above, and are using the latest version of RStudio . You can use {macdown} without RStudio. For example, you can write the Rmd files in your favourite text editor (e.g.  Atom , Notepad++ ). But RStudio is probably the easiest tool for writing both R code and text in your thesis. It also provides a nice way to build your thesis while editing. We’ll proceed assuming that you have decided to use the RStudio workflow.

Install the {bookdown} and {macdown} packages. Note that {macdown} is not available on CRAN and install.packages("macdown") will not work. Use remotes::install_github() as shown below instead to install the package.

Note that you may need to restart RStudio at this point before the template becomes available in the menu.

  • Create a project to work on your thesis! Do not nest your thesis as part of another project, since this will confuse the directory structure.

New RStudio Project

Create your project in a new directory:

Choose New Directory

For the type of project select “Thesis Project using macdown”:

Type of project

  • Customize the information for the thesis in the YAML at the top of index.Rmd. There you can enter your name, title of the thesis, abstract, etc.

Customize information

  • Create R markdown documents with the content of your thesis. Each chapter could be a separate R markdown document. To include in the thesis, use chunks in index.rmd as follows:

Knit the index.Rmd file to get the thesis in PDF format.

Day-to-day writing of your thesis

You need to edit the individual chapter R Markdown files to write your thesis. It’s recommended that you version control your thesis using GitHub if possible. RStudio can also easily sync up with GitHub to make the process easier. While writing, you should git commit your work frequently, after every major activity on your thesis. For example, every few paragraphs or section of text, and after major step of analysis development. You should git push at the end of each work session before you leave your computer or change tasks. For a gentle, novice-friendly guide to getting starting with using Git with R and RStudio, see https://happygitwithr.com/ .

To render your thesis into a PDF, open index.Rmd in RStudio and then click the “knit” button.

The PDF file of your thesis will be deposited in the _book/ directory, by default.

The following components are ones you should edit to customize your thesis:

_bookdown.yml

This is the main configuration file for your thesis. You can change the name of your outputted file here and other options about your thesis here.

This file contains all the meta information that goes at the beginning of your document. You’ll need to edit the top portion of this file (the YAML) to put your name on the first page, the title of your thesis, etc. Note that you need to have at least one chapter start in the index.Rmd file for the build to work. For the template, this is done with # Preface in the example from the template.

01-chap1.Rmd , 02-chap2.Rmd , etc.

These are the Rmd files for each chapter in your dissertation. Write your thesis in these. If you’re writing in RStudio, you may find the wordcount addin useful for getting word counts and readability statistics in R Markdown documents.

Store your bibliography (as bibtex files) here. We recommend using the citr addin and Zotero to efficiently manage and insert citations.

Specific style files for bibliographies should be stored here. A good source for citation styles is https://github.com/citation-style-language/styles#readme .

figure/ and data/

Store your figures and data here and reference them in your R Markdown files. See the bookdown book for details on cross-referencing items using R Markdown.

Where to find more information

If you are new to working with these packages, there is much more information and examples available at {bookdown} and {rmarkdown} .

Writing your thesis

Bernhard bieri.

{iheiddown} ’s primary feature is to enable students of the Institute to write their thesis in R-Markdown. It takes care of the annoying formatting process and automates the most repetitive tasks a student faces when writing scholarly documents. In short, {iheiddown} allows its users to focus on the content rather than the formatting of a thesis.

This guide will show you how to get up and running and start writing your thesis in R while providing you with helpful tips and tricks to make you familiar with the workflow of writing your very own scholarly documents in R.

Installation

The installation process is the same than for the thesis template. You’ll need the following software:

  • Install R and R-Studio
  • For Windows
  • Install {iheiddown} by typing the following command install.packages("iheiddown") in the R-Studio console.

Note: typing remotes::install_github("jhollway/iheiddown") will provide you with the latest version from GitHub.

Create your first thesis project

Creating your first thesis is easy! Let’s look at how it is done. Before we begin, we have to create a new R project by clicking on the file tab in the top of the RStudio window and following the instructions of the prompt that appears. Now that we have created an R project for our presentation, we can open a new R-Markdown file. To do this click on the “plus file” logo in the top left corner and then on “R-Markdown”.

Step 1: Open a project

After you have done this, a little pop-up helper will appear. The first thing we will do is to select the {iheiddown} template for our thesis. To do so, click on the “From Template” option on the left and select the “Thesis {iheiddown}” template. Now give your thesis a name and click on “OK”.

Important note! Name your project index . This makes sure that the main Rmd file is called index.Rmd which is required to render your thesis with our {bookdown} based rendering function. Don’t worry though, you can rename the folder to your project name after creating it.

Step 2: Select a template

Congrats! You just created your first thesis project!

Hold on, this doesn’t look anything like a Word processor!? To see your thesis, you have to “knit” the code by clicking on the little “knit” button while viewing the 00-MyThesis.Rmd file. This will run all the code chunks in every chapter and convert the Markdown code to a correctly formatted PDF document that you will find in the \versions folder of your project.

Take a moment to read through the generated PDF to get acquainted with the {R-Markdown} syntax and to get a feel of the possibilities of {iheiddown} ’s thesis template. This first document is as much a tutorial as this vignette!

Edit your thesis

This section will focus on giving you an overview of the elements of an {iheiddown} thesis and give you a few tips and tricks to edit it.

The different elements of a {iheiddown} thesis

After this initial preview, let’s look at how the thesis project is structured to better understand how to edit it.

The index file

The index file contains two things: the YAML header and the preface of your thesis. It is also the backbone of your thesis in the sense that this is where you will want to knit your whole thesis from.

The YAML header is the place where the main options, metadata and formatting parameters are set. You can set the title of your presentation here, add your name, change the front matter of your thesis (abstract, acknowledgments, table of content, etc.).

The second element in this file is the preface. The only crucial thing to know here is that in order to create your package bibliography (the software you use to render your thesis) you need to leave the first code chunk there.

The chapters

The chapters contain the meat of your thesis, this is where you will outline your idea, run your analyses and draw your conclusions.

Chapters are structured in a similar way, so let us open the 01-introduction.Rmd chapter. In it, you will first find a YAML header that where you can set various chapter level metadata and options.

Note that if for some reason you rename the chapter, you will need to specify the new name in the YAML header too under the input option. Once you have done this you can write away!

The last thing to know about individual chapters is that you can knit them individually. This comes in handy when you want to generate only one part of your thesis for preview purposes.

The appendix and the references files

These files are a bit special as you might notice when you open them.

The 99-references.Rmd file generates the bibliography. This happens automatically, so you will most likely not need to alter this file. Just know that you can set the title of the reference section in the first line.

The 98-appendix.Rmd file allows you to showcase code, additional outputs and more in a separate section to avoid unnecessarily cluttering the main body of your thesis. This can be done by referencing code chunks from your main body and printing the computations you did in your R chunks or by adding new ones.

The _bookdown.yml file

The _bookdown.yml file contains additional information for the YAML header of the main .Rmd file. A standard user should not have to edit it. If for some reason or another you still feel like it, you need to know that you can set additional .Rmd subdirectories, set another output file than the standard \versions file, and toggle the deletion of merged files after the knitting process ended here.

The \bib folder

The bibliography folder contains two files; packages.bib and references.bib . The former is automatically generated by the first code chunk in the index.Rmd file and cites the packages you have loaded when running your code chunks. You will not need to alter this.

On the other hand, the references.bib file is the place to dump the bibtex citations that you will cite in your thesis.

The \data folder

The data folder is the place to put all the data that you use in the code chunk of your analysis. Remember to keep it tidy so you can easily link data to outputs down the line such as graphs and tables.

The \figures folder

The figures folder will contain all the graphical elements that you may want to include in your thesis e.g. figures, graphs, or images. It also contains a file named SecretariatDocument.pdf that you will need to replace with the one that was handed to you by the PhD or Master’s secretariat. Remember to rename the file you got from the secretariat as SecretariatDocument.pdf . Otherwise {iheiddown} will not recognize it.

The \front-matter folder

The front matter folder contains the front matter of your thesis. This is where you will be able to edit the abbreviations part in the corresponding Latex file, the acknowledgments section or the abstract of your thesis in their respective .Rmd files.

The \versions folder

This is where you will find the pdf file after your thesis has been knitted by {iheiddown} .

Additional resources

Here is a list of additional links that will help you get familiar with our {iheiddown} thesis template, {bookdown} and Markdown syntax.

  • R-Markdown Cookbook
  • Bookdown book
  • Markdown guide

Tips on Writing Thesis in RMarkdown

Kaining zhou, 14 february, 2022, 1. to live preview the output without kniting the file.

xaringan::inf_mr()

2. Include code but not run in RMarkdown output

Add back ticks `` around the code.

3. Comment out text

Manually put signs around your comment like: <!-- your comment -->

Use the keyboard shortcut Ctrl + Shift + C to comment out a line of text.

4. Push local changes to GitHub

In RStudio, Tools > Shell

Type these command lines one by one:

5. Indent text

whitespaces are often meaningless in Markdown. Markdown will also ignore spaces used for indentation by default. However, we can use line blocks by starting the line with a vertical bar (|). The line breaks and any leading spaces will be preserved in the output. For example:

The output is:

6. Insert bibliographies and citations

Specify a bibliography file (make sure you choose the same folder as where your R Markdown document lives) using the bibliography metadata field in YAML. For example:

where the BibTeX database is a plain-text file with the *.bib extension that consists of bibliography entries like this:

Items can be cited directly within the documentation using the syntax @key where key is the citation key in the first line of the entry, e.g., @R-base . To put citations in parentheses, use [@key] . To cite multiple entries, separate the keys by semicolons, e.g., [@key-1; @key-2; @key-3] . To suppress the mention of the author, add a minus sign before @, e.g., [-@R-base] .

7. Insert citations from Google Scholar

  • Find an article you are interested
  • Under the return result of that article, click Cite then BibTex , then copy the content then paste to your references.bib file.
  • Cite this article in your Rmarkdown

8. Insert citations from Mendeley

Open Mendeley and select Mendeley > Tools > Options > BibTeX . Select Escape LaTeX special characters , Enable BibTeX syncing and Create one BibTeX file for my whole library .

Make sure you choose the same folder as where your R Markdown document lives. If you don’t want to do that, it is no longer automatically synced if you change something in Mendeley, so you’ll have to do update the bibtex file manually.

Now go to the R Mmarkdown document. In the YAML header, write ‘bibliography: library.bib’ , so your header will look like something this:

In Mendeley, check the citation key of the paper you want to cite (in the Document Details tab). In your R Markdown document, write the citation key in square brackets, for example [@Author2000] .

9. Debug when fail to insert citations from Mendeley

Sometimes the article which exists in Mendeley can not be found in library.bib . Now it is worth checking whether this article is in the folder named Needs Review in Mendeley. Needs Review lists any items which Mendeley has imported, but may require extra attention.

Once you review the details and indicate that they’re correct, it will be removed from this list and automatically synced in your library.bib .

10. Find high quality BGU graphic materials, logos, and presentations

BGU logos are in both pdf and png format.

11. After adopt Oxforddown and write my own, compare with the original pdf output

Oxforddown pdf output

Useful references:

  • R Markdown Cookbook .
  • Thesis template Oxforddown
  • Oxforddown learning video tutorial
  • bs4 format Tutorial on how to use Oxforddown

Writing a thesis in R Markdown

March 14, 2020

A short discussion about my experiences using R Markdown to write my PhD thesis.

At the start of my PhD I had never even heard of R/R Markdown let alone considered using it to write my thesis. However, thanks in part to the numerous amount of resources out there showing what is possible within R for writing lengthy technical documents, I made the decision to give it a go - and haven’t looked back since.

The purpose of this post is to pay homage to the resources I used throughout writing my PhD and highlight some of the issues I came across while doing so, in the hope that a future reader may find something useful…

My only advice to someone who was considering using R Markdown to write a thesis would be just go for it - there are ample resources out there to help, and the process is incredibly rewarding.

For those interested, the repository of my completed thesis can be found here: https://github.com/hfshr/phd-thesis

Combine text and code

The ability to integrate text and R code in the same document to produce tables and figures is extremely useful. No more copy/pasting from Excel to Word for tables and figures!

Separate files for each chapter

Large word documents can quickly become unwieldy, and increasingly frustrating to work with as the document grows in length. R Markdown lets you easily combine multiple chapters/files into one document when you press knit.

Learn a new skill

I found writing in Markdown really satisfying. Writing a thesis can certainly be a little dull at times, but there were always new things to learn while using Markdown, and this certainly helped keep me motivated when writing wasn’t going so well…

Potential downsides

This was the only major issue I faced using Markdown. While my supervisors were happy enough for me to use R Markdown, they were not too keen on learning how to use git and start opening pull requests on my draft chapters… So for feedback, I ended up knitting to .docx so comments could be tracked using Microsoft word. The downside to this was that formatting often went astray, but over time they were ok with this after seeing the aesthetically pleasing PDF outputs that were possible.

Inevitably you will need to learn some LaTeX

R markdown does a fantastic job and can get you 95% of the way there without ever having to open a .tex file. However there will likely be some fine tuning that is either not easy or not possible to do with R Markdown, and using If unfamiliar with LaTeX, this can be a steep learning curve, but there are ample resources out there to help figure things out.

Potential to get distracted from writing

Occasionally I would spend time fiddling with the layout of certain pages, or trying to get a specific table looking a certain way, when I really should have just saved that till after the writing was finished. My tip would be dedicate time to writing and time to editing and try not to mix the two. That way you can dedicate your full focus to each task, and not get distracted by one when you need to be working on the other.

Below are some of the key resources I used during my write up.

  • R Markdown: Providing the tools Xie, Allaire, and Grolemund ( 2018 )
  • Bookdown: Excellent package by yihui for writing all kinds of documents Xie ( 2016 ) https://github.com/rstudio/bookdown
  • Thesisdown: Extension to bookdown focusing specifically on thesis style documents https://github.com/ismayc/thesisdown Solomon ( 2020 )
  • Really useful blog by Ed Berry I found early on in R markdown journey (Thanks Ed) https://eddjberry.netlify.com/post/writing-your-thesis-with-bookdown/
  • Another useful blog for some additional formatting tips https://rpubs.com/theycke/380678
  • Papaja: Fantastic package for formatting in APA style https://github.com/crsh/papaja Aust and Barth ( 2018 )

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Template for writing an Oxford University thesis in R Markdown; uses the OxThesis LaTeX template and was inspired by thesisdown.

ulyngs/oxforddown

Folders and files, repository files navigation.

I encourage someone to fork this repository and make it work with Quarto! :)

How to cite

If you use this template to write your thesis, please cite it! 🥰 (and/or click 'Sponsor' and buy me a coffee... 😉 )

DOI

Requirements

How-to chapters, video tutorials, writing your thesis.

  • Gitbook output
  • BS4 book output

Word output

Building a single chapter, customisations and extensions, output formats.

A template for writing an Oxford University thesis in R Markdown. The template uses the bookdown R package together with the OxThesis LaTeX template , plus lots of inspiration from thesisdown .

  • Sample PDF output
  • Sample BS4 book output

Examples of theses written with oxforddown (see also Google Scholar ):

  • Ulysses in Cyberspace: Examining the Effectiveness of Design Patterns for Digital Self-Control by Ulrik Lyngs
  • The impact of heat on occupational injuries, illnesses and associated economic costs in Australia by Matthew Anthony Borg
  • The Psychology of Managerial Capital Allocation by Shir Dekel
  • Teens, Screens and Wellbeing: An Improved Approach by Amy Orben
  • Interpreting Neural Language Models for Linguistic Complexity Assessment by Gabriele Sarti
  • Modeling of nutrient dynamics in an urbanized tropical estuary and application to eutrophication risk management by Nguyen Truong An

NOTE: If you've used this template to write your thesis, drop me a line at [email protected] and I'll add a link showcasing it!

R and RStudio version 1.2 or higher

The R packages rmarkdown , bookdown , tidyverse , kableExtra , and here

a LaTeX installation

Option 1: Use TinyTeX (a minimal LaTeX installation intended for use with R Markdown)

  • the development version of TinyTex is currently required . Install from R with
  • Then install the LaTeX packages used by oxforddown (diskspace taken up by TinyTex with the required packages installed is about 280 Mb)

Option 2: Use an ordinary LaTeX distribution

  • Mac: download and install MacTeX from tug.org/mactex/ (~4 gigs)
  • Windows: download and install MikTex from miktex.org
  • Command line developer tools. If you haven't got these installed already, your mac will probably automatically prompt you to install them. Otherwise, you can install them by opening a terminal and typing xcode-select --install
  • download the ulyngs/oxforddown repo as a zip
  • open oxforddown.Rproj in RStudio

Read the 'How to use' chapter to understand the structure of oxforddown and how to do the basic things like building your thesis.

Note: bibliography files cannot have underscores in their names!

For how to use R Markdown syntax in general and in oxforddown in particular, read the dedicated chapters on this ( R Markdown basics , Citations, cross-references, and collaboration , and Tables ).

See also the general, official R Markdown resources R Markdown: The Definitive Guide and the R Markdown Cookbook .

I am in the process of updating the tutorial videos to v3 - I've noted below which have yet to be updated, but are still informative, and struck out those that no longer apply:

  • Part 1: Building the entire thesis
  • Part 2: Building a single chapter
  • ( old but informative ) Part 3: Understanding the file structure
  • ( old but informative ) Part 4: A walk-through example of creating your thesis
  • Part 5: The content included in index.Rmd (or: why the introduction chapter is special)
  • ( old but informative ) Part 6: Adjusting the order of chapters
  • ( old but informative ) Part 7: _bookdown.yml: Adjusting build settings
  • Part 8: Makefile: Adjusting build settings
  • ( old but informative ) Part 9: The LaTeX templates
  • update the YAML header (the stuff at the top between '---') in index.Rmd with your name, college, etc.
  • write the individual chapters as .Rmd files in the root folder
  • write the front matter (abstract, acknowledgements, abbreviations) and back matter (appendices) by adjusting the .Rmd files in the front-and-back-matter/ folder

.Rmd files you don't want included in the body text must be given file names that begin with an underscore (e.g. front-and-back-matter/_abstract.Rmd and front-and-back-matter/_acknowledgements.Rmd ). (Alternatively, specify manually in _bookdown.yml which files should be merged into the body text.)

Building your entire thesis

  • Build the entire thesis by opening index.Rmd and clicking the 'knit' button.
  • The generated thesis files are saved in the docs/ folder
  • To choose output formats, go to the top of index.Rmd 's YAML header and edit the line thesis_formats <- "pdf"; to the format(s) you want (options are "pdf", "bs4", "gitbook", and "word")
  • You can build to multiple formats simultaneously with, e.g., thesis_formats <- c("pdf", "bs4", "word")
  • If you want to customise the build function, edit scripts_and_filters/knit-functions.R

writing thesis in r markdown

When you build the entire thesis to PDF, Latex generates a whole bunch of auxillary files - these are automatically removed after the build process end by the custom knit function that is used when you knit index.Rmd .

To change how this removal is done, edit scripts_and_filters/knit-functions.R . The line file.remove(list.files(pattern = "*\\.(log|mtc\\d*|maf|aux|bcf|lof|lot|out|toc)$")) within if ("pdf" %in% output_format){ is the one that removes files after PDF output is generated.

BS4 book output (HTML)

  • NOTE: the bs4 book output requires the downlit and bslib R packages (install them with install.packages )
  • Note also that to deploy a BS4 book on GitHub Pages, there must be a .nojekyll file in the docs/ folder, otherwise GitHub does some voodoo that causes some filepaths not to work. This file is generated automatically by oxforddown 's knitting function.

Gitbook output (HTML)

  • Note that to deploy a gitbook on GitHub Pages, there must be a .nojekyll file in the docs/ folder, otherwise GitHub does some voodoo that causes some filepaths not to work. This file is generated automatically by oxforddown 's knitting function.
  • Note that the Word output has no templates behind it, and many things do not work (e.g. image rotation, highlighting corrections). I encourage pull requests that optimise the Word output, e.g. by using tools from the officer package.

To knit an individual chapter without compiling the entire thesis:

  • open the .Rmd file of a chapter
  • add a YAML header specifying the output format(s) (e.g. bookdown::word_document2 for a word document you might want to upload to Google Docs for feedback from collaborators)
  • click the knit button (the output file is then saved in the root folder)

As shown in the sample chapters' YAML headers, to output a single chapter to PDF, use e.g.:

The file templates/brief_template.tex formats the chapter in the OxThesis style but without including the front matter (table of contents, abstract, etc).

NOTE: The bibliography path in your individual chapters' YAML headers needs to be identical to the one in index.Rmd - otherwise your individual chapters' bibliography path may override the path in index.Rmd and cause trouble when you knit the entire thesis.

  • for common things you might want to do in your thesis, read through the sample content
  • the 'Customisations and extensions' chapter (thanks @bmvandoren!) has tips on how to include PDF pages from a published typeset article in your thesis, and much more!

Limitations

don't use underscores (_) in your YAML front matter or code chunk labels! (underscores have special meaning in LaTeX, so therefore you are likely to get an error, cf. https://yihui.org/en/2018/03/space-pain/ )

  • bad YAML: bibliography: bib_final.bib
  • good YAML: bibliography: bib-final.bib
  • bad chunk label: {r my_plot}
  • good chunk label: {r my-plot}
  • at the moment only PDF and HTML output have been properly implemented; I may improve on the Word output further down the line

Releases 11

Sponsor this project, contributors 5.

R Markdown Cookbook

Chapter 5 formatting.

The greatest strength of the Markdown language is that its simplicity makes it very easy to read and write even to newcomers. This is its key design principle, as outlined by the creator of the original Markdown language:

A Markdown-formatted document should be publishable as-is, as plain text, without looking like it’s been marked up with tags or formatting instructions. — John Gruber

However, this comes at a cost of customization. Many features of typical word processors are not directly available in Markdown, e.g.,

changing the font size of a piece of text;

changing the font color of certain words;

specifying text alignment.

We leave it to you to decide whether such features are worth your effort. To some degree, Markdown reflects the philosophy of Stoicism: the “natural world” consists of plain text, and you should not be controlled by the desire for (visual) pleasure. Anyway, this chapter offers some tips on how you can customize the appearance and styling of elements in an R Markdown document.

If you need a reminder in the basics of the Markdown language, the R Markdown cheatsheet at https://www.rstudio.com/resources/cheatsheets/ provides a good overview of the basic syntax.

Writing a Master's thesis with R Markdown and Bookdown

Posted on 16 July, 2020 at 00:00 UTC by Etienne Bacher

Why bookdown ?

Latex packages and commands, titlepage, acknowledgements and abstract, include latex files in yaml.

I finished my Master’s thesis very recently, and I wrote it with R Markdown, and more precisely with the bookdown package. It was really comfortable to do absolutely everything with R: data treatment, use of econometric methods, redaction with chunk of codes, and even the slides for the presentation! However, I have also spent a non-negligible part of my time trying to have a correct layout, essentially for the first pages. I found that some things were not as easy to do as they should be. This post contains some solutions to these problems.

A small preamble before starting to list these problems and solutions: why did I use bookdown and not rmarkdown ? bookdown has a few advantages that are very important when writing a Master’s thesis (or an academic paper in general), such as cross-references between sections, figures, tables, etc. See the bookdown book for all the details.

While it is possible to create a bookdown project with RStudio, I “manually” made my own, because I have the impression there are a lot of files created automatically by RStudio that would just confuse myself. Therefore, I had a file containing the YAML and the chunks necessary to load all the packages needed and to run the child documents. Child documents are .Rmd files that contain only some Markdown text and code chunks (no YAML). They make it much easier to write a thesis since it is possible to divide it in several pieces (introduction, literature review, method, etc.).

In addition to Global.Rmd (which contains YAML and setup chunks), I used two .tex files: preamble.tex is where I put all the LaTeX commands and packages I used, and titlepage.tex to make my custom titlepage, acknowledgments and abstract before the table of contents.

In preamble.tex , I put all the LaTeX commands, many of them being \usepackage . For example, the R package kableExtra provides a list of LaTeX packages required to be able to customize the tables (see here ).

Here’s a small list of the commands I used for my thesis.

\renewcommand{\baselinestretch}{1.3} to change the space between lines;

\pagenumbering{gobble} to remove page numbering for the first pages, that contain the title, the table of content (TOC), the lists of figures and tables (LOF and LOT) and some blank pages. I used \pagenumbering{arabic} after the YAML to start the page numbering at the right place.

\usepackage{caption} ; \captionsetup[table]{name=Tableau} ; \captionsetup[figure]{name=Figure} . These three commands (to put on three separate lines) are here to change the name of tables and figures. If you’re writing in English, you probably won’t need them, but they were necessary to write in French.

the following lines create a new command to create a blank page after the titlepage. Strangely, \pagebreak or \newpage didn’t work inside the titlepage and I had to find an alternative:

\usepackage{afterpage} \newcommand\blankpage{% \null \thispagestyle{empty}% \addtocounter{page}{-1}% \newpage}

Concerning these three components, I put them in another file named titlepage.tex . This is the layout I wanted:

a titlepage with some logos and some information on my thesis and my university;

a blank page;

acknowledgements on a new page;

abstract on a new page;

TOC, LOF and LOT on a new page.

To do so, I started the titlepage with \begin{titlepage} and customized it as I wanted. But before putting \end{titlepage} , I placed \afterpage{\blankpage} , which is the command we define in preamble.tex . With this, I had a titlepage and a blank page.

The next step was to create two pages containing the acknowledgements and the abstract This was easily done in LaTeX, and this time I could use \pagebreak at the end of the acknowledgements to create a new page for the abstract. I also put another \pagebreak to finish titlepage.tex , so that TOC, LOF and LOT (created in the YAML) could start on a new page.

As explained, I had two .tex files to run when compiling the R Markdown file:

preamble.tex is a list of commands that should be placed before \begin{document} when this .Rmd file will be converted to .tex . Therefore, I used in_header in the YAML to compile it.

titlepage.tex contains some elements that should be in the final PDF document. Since this should appear first (before the rest of the .Rmd document), I used before_body in the YAML.

Here are examples of the three files: Global.Rmd , preamble.tex and titlepage.tex .

--- output: bookdown::pdf_book: includes: in_header: preamble.tex before_body: titlepage.tex keep_tex: true toc: yes toc_depth: 3 indent: true link-citations: yes lot: true lof: true --- <!-- Start the redaction on a new page --> \newpage <!-- Start page numbering where the redaction starts --> \pagenumbering{arabic} ```{r globaloptions, include=FALSE} # Include here chunk options ``` ```{r packages} # Load here the packages ``` <!-- Call the child documents --> ```{r body, child = c('01-Intro.Rmd', '02-Literature.Rmd', '03-Data-and-method.Rmd', '04-Results.Rmd', '05-Discussion.Rmd', '06-Conclusion.Rmd')} ``` <!-- Placement of bibliography --> # References {-} <div id="refs"></div> <!-- Place the appendix after the bibliography --> ```{r appendix, child = c('07--Appendix.Rmd')} ```

% Line spacing \renewcommand{\baselinestretch}{1.3} % Page number and chapter at the top of the page \pagestyle{headings} % Important packages \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage[dvipsnames]{xcolor} \usepackage{hyperref} \usepackage{dcolumn} \usepackage{booktabs} \usepackage{longtable} % Figure and table names \usepackage{caption} \captionsetup[table]{name=Tableau} \captionsetup[figure]{name=Figure} % Packages for kableExtra \usepackage{array} \usepackage{multirow} \usepackage{wrapfig} \usepackage{colortbl} \usepackage{pdflscape} \usepackage{float} \usepackage{tabu} \usepackage{threeparttable} \usepackage{threeparttablex} \usepackage[normalem]{ulem} \usepackage{makecell} % Remove page numbering before start of redaction \pagenumbering{gobble} % Command to make a blank page \usepackage{afterpage} \newcommand\blankpage{% \null \thispagestyle{empty}% \addtocounter{page}{-1}% \newpage}

\begin{titlepage} \centering Title of my thesis \afterpage{\blankpage} \end{titlepage} \section*{Acknowledgements} Thanks everyone \pagebreak \begin{center} \textbf{Abstract} \end{center} Bla bla bla... \pagebreak

Hope this helps!

Etienne Bacher

Clermont-Ferrand , France Email me

I'm a French student in Economics, currently finishing my Master's degree.

Copyright © 2020, Etienne Bacher. Built with Blogdown. Powered by indigo theme for Hugo

Information Technology

Writing Your Thesis in R Markdown

Another option is to write your thesis using R Markdown. This might be particularly useful for you if you plan on using a number of R features in your thesis and would like to be able to change your code without having to completely update your old thesis document.

If you have worked with R before, this may be easier to work with than the LaTeX template, still using the same engine to typeset the thesis, allowing for a pleasant presentation of final results.

Should you wish to write your thesis in R Markdown, please go to this GitHub page for the instructions on how to use the R Markdown to write your thesis using package thesisdown . 

For help using the R markdown template, stop by the mLab during (virutal) open hours.

Academic Writing in R Markdown II

Writing my PhD Thesis in R Markdown

As a researcher that has found out about the marvels of R Markdown , how can you go about writing a book ? I offer here my experience writing my own PhD thesis in R Markdown. I must remark that by the time I started writing my dissertation I had some solid experience with R Markdown and R, which helped a lot. Learning R Markdown while struggling with your thesis might not be the best idea, unless —a bit like me— you like figuring out formatting tools as a productive procrastination activity that clears your mind from other taxing aspects of writing.

In each section of this post I will look at a few things of interest that are particular to writing thesis in bookdown (the package to write books in R Markdown) or that I found particularly useful and interesting for my experience.

Output: HTML/PDF

The bookdown package supports three main formats : HTML, PDF and e-books. I will only talk about the first two because they are the ones I used. I knew from the beginning that I wanted at least those two formats: PDF for the printed version that I would have to hand in and HTML to show it to the world in a digital version, like all those other online books I was loving to find. However, I first focused on the HTML only because when I started looking into bookdown I found this :

We strongly recommend that you use an HTML output format instead of LaTeX when you develop a book, since you will not be too distracted by the typesetting details, which can bother you a lot if you constantly look at the PDF output of a book. Leave the job of careful typesetting to the very end (ideally after you have really finished the content of the book).

I agree that HTML output is more reliable in terms of formatting, while \(\LaTeX\) (PDF) output can have some weird stuff that will put you off, such as ugly or not well positioned tables (that looked so good in the HTML version!) or code that runs out of the margins if you use code-snippets. However , I do recommend generating the PDF output anyways, just to check that it compiles . HTML is more lenient than PDF in that it will (almost) always run and at most show you funky output in cases where \(\LaTeX\) will just crash with an error message that you will probably not understand. Such issues can often be resolved by reinstalling stuff , but sometimes it’s a simple thing like some weird symbol in your table. You don’t want to write your whole thesis (or even half of it) and then realize that the PDF just doesn’t compile, because you won’t solve that in just a few hours. That is why I recommend running the PDF anyways, to make sure it is birthed properly, but still look at the output in HTML only (which will always be beautiful and make you happy).

Regarding HTML, I like the bs4-book format the most 1 , among other things because of the secondary menu on the right and the pop-up footnotes. I changed the primary color to #086a6a and then every time I created the HTML it just filled me with joy. Whatever I wrote, it looked gorgeous and professional, and all I had to do was type it. It really makes your day.

Finally, if you need to ask for feedback, writing comments on an HTML file is not something many people know how to do , so you will want to create the PDF. In any case, one of the advantages of R Markdown is that you can use the exact same input to generate both outputs! There are few things that don’t work exactly the same, though, that I will discuss below , such as features of tables that are specific to one format, or matching the font in your graphs to the font in the rest of your text. Fortunately, the knitr package (that works with rmarkdown ) offers you the functions is_html_output() and is_latex_output() , which return TRUE when the outputs are HTML and \(\LaTeX\) respectively and FALSE otherwise. You can use these functions to make your plots and tables adapt to the format of your output.

Macro organization: chapters and frontmatter

A book typically has chapters. As such, bookdown treats the multiple .Rmd files in your project as chapters that are unified in the final product. For an HTML book, this is going to be a website with different HTML pages but one unifying menu or table of contents. Here you must distinguish between the title of your chapter and the name of the file. For example, Chapters 2, 3 and 4 of my dissertation are called “From corpora to clouds”, “Visualization tools” and “Case studies”, but the files are called “workflow”, “nephovis” and “dataset” respectively, with .Rmd extension in the R Markdown version and .html extension when rendered. This means that I can use code names related to the kind of content in my chapter for the names of the files, but then change the title of the chapter as much as I want without any issues. It also means that you will only actually see the original name of my file if you look at the URL (e.g.  https://cloudspotting.marianamontes.me/dataset.html ), but you will mostly pay attention to the title (“Case studies”) or even the title in the tab of your browser (“Chapter 4 Case studies | Cloudspotting”). The PDF version of the book, on the other hand, is only one file with consecutive page numbering, and the original file names are nowhere to be seen.

Note that, by default, bookdown will merge all the .Rmd files in your project in alphabetical order, but you can override that by listing your desired files in the desired order in the _bookdown.yml configuration file (see this doc ). This is particularly handy if you want to only select one or a few chapters to show to someone in PDF, as I learned after painstakingly trying to print-to-PDF selected pages of my PDF.

Chapters are, of course, not the only unit in which to divide your text. At a higher level, you can have parts and appendices , which make a nice division in the HTML table of contents and get their own pages in the PDF output. At a lower level, you can have sections and subsections, which you create by lowering the level of the headings: from # for the title of the chapter to ## to the first subheader, then ### and so on. Chapters will be automatically numbered, but you can un-number them by adding a {-} at the end, e.g. for a preface or the references section. When they are numbered, you can set whether the number is preceded by Chapter or maybe Capítulo , Capitolo , Hoofdstuk , etc., by editing the _bookdown.yml configuration file.

For cross-referencing chapters, sections and subsections, I suggest adding a code name to the section as well. For example, you may have a temporary heading “The methodological part” to which you assign the codename “methods”:

Anywhere else in your book, you can reference that title with \@ref(methods) , which will then be replaced by the correct numbering with a hyperlink to the appropriate header, e.g. “3” if it’s Chapter 3, “3.2” if it’s the second section of chapter 3, etc. You can move the heading, change its level (e.g. from 3.2 to 3.1.2), change the title itself —yet, as long as the codename between the curly braces remains the same, the cross-reference will adapt and keep working from anywhere in your book . And if you eventually post the HTML version online, you can even have an URL that takes you to that section, like this link to section 6.2.3 in my thesis (how cool is that?!).

A final amazing point of sections within chapters is that, in R Studio, you can keep track of your internal organization with a small outline on the right side and you can even collapse a section, that is, hide the content while you are editing. In the image below, for example, you can see the outline of the forth chapter of my thesis and that the third level headings “The nouns”, “The adjectives” and “The verbs” are collapsed: their content is hidden and a yellow box with a double-headed arrow shows up in its stead. I achieved this by clicking on the tiny triangles next to the headings. As a result, I can move around a file more easily, skipping long sections that I don’t want to deal with yet.

Figure 1: Outline and collapsed sections in R Studio editor.

I want to close this section with a very technical adventure: how to add a personalized frontmatter to the PDF output. At the beginning of the thesis, I needed a mandatory title page required by the Faculty, but I also wanted to add a page with a dedication, a list of figures, a list of tables (because I’m demanding like that) and, as if that was not enough, I wanted them, the preface (my abstract) and acknowledgements sections to be numbered with those lowercase roman numbers, so that the first page of Chapter 1 was “page 1” instead. But, because it is quite technical and not something you would worry about until the end, it’s collapsed under the following paragraph.

Adding a frontmatter (in PDF)

First, I have two .tex (raw \(\LaTeX\) files) that you can just copy and adjust with your own data. There is preamble.tex and titlepage.tex , which are then referenced in the _output.yml configuration file:

The preamble.tex file has a bunch of \(\LaTeX\) instructions, starting with a number of packages that are loaded:

  • \usepackage[backend=biber, style=unified,maxcitenames=3,maxbibnames=99]{biblatex} to deal with citations , in particular the Unified Stylesheet for Linguistics
  • \usepackage[nottoc]{tocbibind} for lists of tables and figures (see docs )
  • \usepackage{fancyhdr} for fancier headers; I suggest checking Overleaf docs to learn more about it.

It also sets up a nice dedication format. Whatever you change here will have to do with the formatting itself, but I recommend googling suggestions to see how you would want to change them. If you like what it looks like in my thesis , then don’t change anything.

The titlepage.tex has actual content. The first line, with the \includepdf{} command, adds a frontcover ; a similar line is found as the only content of afterbody.tex for the back cover. Then I set up the title page adding the Faculty logo and the different pieces of text that I need. Those you should adapt to your own text —take into account that you will need to change the paths to the images. Then I add empty pages with \newpage and finally a separated page with the dedication, that you will have to adapt as well (unless you also want to dedicate your thesis to my parents: your choice). At the end of the file there is a command, \frontmatter , that starts the frontmatter proper: everything after that will automatically receive the lowercase roman numbers. As you can see in the file of my acknowledgements , I end the frontmatter with the \mainmatter command (the rest of the \(\LaTeX\) code is to adjust the headers), so that the normal numbering starts.

The lists of figures ( lof ) and tables ( lot ) are then activated in the YAML of index.Rmd , where I also include some instructions for the size and margins of the pages using the geometry package :

Rendering your data: tables, plots and more

One of the things I like the most about R Markdown is that I can generate my tables and plots writing a bit of code in the same file where I am writing the rest of my text. The link between the data and the rendering is never erased. I will not talk about how to do that, but I do want to list some resources that have made the experience more enjoyable, mostly by making everything prettier.

First, one way of rendering a table is with the kable() function of the knitr package ( Xie 2021b ) , and it’s OK. But then there is kableExtra ( Zhu 2021 ) , which has amazing functionalities to play with tables both in HTML and in \(\LaTeX\) , such as merging columns or rows, conditional formatting, footnotes, plots inside your table , etc. Some things will work the same way for both formats, while others will not. Most notably, in PDF it is relevant to make a very long table span over multiple pages or a very wide table to be shown in its own landscape page; in HTML, instead, you would prefer a scrollbox: only a limited space is used for the table and the reader can scroll down or to the side to see more content. The kableExtra package offers all these options.

Something I didn’t know until I was fixing the formatting of my thesis is that, while \(\LaTeX\) can be very smart at positioning your figures without leaving huge blank spaces, it does not do the same with tables. I did have to move some text around to fit the tables with the flow.

When creating plots, I like using the ggplot2 package and its multiple extensions for specific kinds of graphs. I also discovered ggpubr ( Kassambara 2020 ) , and I used its theme_pubr() for very neat theming of my plots. 2 For most of my graphs, I used Okabe and Ito ( 2002 ) ’s colorblind-friendly color scheme, available as colorblindr::scale_OkabeIto() ( McWhite and Wilke 2021 ) , but I also used the viridis scales . 3 Another useful package is cowplot ( Wilke 2021 ) , from which I use plot_grid() to bring several plots together in one figure and other functions to create marginal plots (plots in the margins of other plots).

An interesting thing I noticed late into the formatting of my thesis was that the default font of the plots matched the HTML default font very well, but not the serif default font in the PDF output. After a bit of digging I decided that “Bookman Old Style” was the font that I could get that matched the PDF output the best, so I followed the instructions of the extrafont package ( Winston Chang 2014 ) , set a plot_text variable dependent on the output of the file, and then used it in theming functions such as ggpubr::theme_pubr() when I created some plot, or in cowplot::plot_grid() when I labeled the plots I was grouping.

Setting up variables like this and creating functions can help you generate multiple plots with consistent format.

As I mentioned before , one winning feature of R Markdown is that you don’t need to rearrange tables and figures to fit the flow of the text. This is trivial in HTML, where each file is a virtually endless page to scroll down through, so tables and figures simply appear where you want them to. In PDF, figures may be moved around so they are not split by a change of page, and tables may be moved to the start of the following page. So, this shouldn’t worry you. However, some people fret about the position of tables and figures because they may use references such as “the following figure” or “this table”, which I may use in a post like this but is not really appropriate in an academic setting. Instead, you want cross-references. I already mentioned how to reference a heading; referencing figures, plots or even equations is not very different, except that the code name must be prefixed by fig , tab and eq , respectively. For example, I could reference the figure above, Figure 1 , which I simply called myfig , by typing \@ref(fig:myfig) . This produces the number, and I have to manually precede it with “Figure”. The code name is the name of the R chunk with which you generated the figure/table:

Another neat addition of bookdown is the use of references for captions. Normally, you would add the caption to a figure as a fig.cap chunk option, and to a table as a caption argument in kable() , but then you don’t have much room for formatting. The alternative is to create a reference as a line in R Markdown starting like (ref:figname) , and then use '(ref:figname)' where you would have used the caption. That way, you can write longer and fancier captions and avoid cluttered chunk options. For example, the code below (without the space between ref: and mycats ) will generate Figure 2 , which is referenced as Figure \@ref(fig:mycats) .

Figure 2: These are my cats, Chi is black and Sai is tabby.

So academic: citations!

A great deal of academic writing involves interacting with other research, mainly through citations. This is extremely simple with R Markdown, especially if you use Zotero and even more if you enhance it with Better BibTex: I talked about it before .

As the documentation shows, citing in R Markdown follows pandoc’s system and is pretty straightforward. Basically you have a citation key, e.g.  montes_2021 , you precede it with @ if you want to integrate it in the text as Montes ( 2021 ) , and then you can also surround it with [ ] if you want it in parentheses ( Montes 2021 ) and precede it with - if you want to exclude the name, because you mentioned it before: ( 2021 ) . In order to add a page number, you just place it between square brackets ( @montes_2021 [50] generates Montes ( 2021, 50 ) ) or, if you’re already inside, separate them by a comma ( [@montes_2021,50] generates ( Montes 2021, 50 ) 4 ), and if you want to list multiple sources next to each other you can just separate them with semicolons ( [@R-rmarkdown; @R-bookdown] generates ( Allaire et al. 2021 ; Xie 2021a ) 5 ).

R Markdown needs two sources of information: the .bib file with all your entries in BibTex format and your .csl file with the citation stylesheet format. This is taken care of in the YAML of the index.html , in my case with the bibliography , biblio-style (for PDF) and csl (for HTML) fields.

The bibliography field lists two .bib files: the first is a collection of Zotero entries that I exported as BibTex, while the second I generated with knitr::write_bib() to obtain the correct citations of all the R packages I had used. The biblio-style field is the one that talks to biber and the biblatex citation package as specified in both _output.yml and preamble.tex (as I showed before ). For the HTML output I used the .csl file (downloaded, if I’m not mistaken, from Zotero itself). In both cases I’m referencing the Unified Stylesheet for Linguistics. In any case, it is very neat that you can just write all your references and your full text and only take care of the precise stylesheet at the end or when you want to procrastinate with this kind of minutiae. Your full text will adjust accordingly.

Note that certain stylesheets may include instructions on the order of sources when you cite multiple ones at the same time (order in which you typed? Family name? Year?). When you write a prefix between the brackets, e.g.  [cf. @source1, @source2] , if that source is moved around, so is the prefix.

I would like to close this section with a note on formatting, not always ‘citations’ per se. First:

In case you are not that familiar with markdown, you can easily create a blockquote by prefixing the paragraph with > .

Second, if you are writing about linguistics , you will probably want to include linguistic examples. Here I have good news and bad news. As far as I know, there is \(\LaTeX\) support for glosses , but no nice tool for HTML. If there is demand, I suppose it could be created. If you don’t need glosses but still would benefit of linguistic examples such as (1) below, Pandoc does have you covered . You precede your sentence with a codename in parentheses and starting with @ (e.g.  (@ex1) This is a linguistic example ) and then you can reference it anywhere as (@ex1) . Note that, like for figures, tables, etc., the key you are referencing does not to be numbered, and if you move your example around the numbering will update automatically. The resulting number assigned to each example is consecutive across your full book based on order of appearance. It is surrounded by parenthesis in the PDF format but looks like a normal numbered list in HTML. I’ve found code to fix that in HTML when you have one file, but not for a book. If anyone has ideas on how to customize it, I’m interested!

  • This is a linguistic example.

Finally: a cover

OMG you’re done already?! You have a nice cover and all! 6

I only added the cover to my PDF output after sending it to print, when I had to send a digital version. I had a PDF for the front cover and one for the back, and I added them with the \includepdf{} \(\LaTeX\) command at the beginning of titlepage.tex and as only content of afterbody.tex , which are called in the _output.yml configuration file.

For the HTML version, I only added the cover when I made my thesis public after my defense (and I didn’t generate a PDF afterwards). Imitating the source code of one of Hadley Wickam’s books 7 I added ![Cover image](front-cover.png){.cover width=250} after the title of the Preface (in index.Rmd ). I understand that .cover is a CSS class that takes care of all the beauty and neatness of how the cover is presented. In the original case I think the image is also a hyperlink to the Amazon page where you can buy the book (I probably should make mine a hyperlink to my pdf…).

Good luck with yours! I hope this post encourages you and helps you to try to write your own thesis, or a book, or anything else, in R Markdown too!

I’m quite sure that the documentation section about this format did not exist yet in the Bookdown book when I started my thesis and I had to do some digging to figure out how it was named. I’m happy it has more documentation now! ↩︎

It also has functions for very typical plots, making it easier for example to create a boxplot and show the significance of the difference between groups. ↩︎

Even more recently I discovered the color palettes of ggsci , but I haven’t used them yet. ↩︎

How pages are indicated depend on the citation stylesheet. ↩︎

Note that R Markdown adds the a at the end by itself. ↩︎

I used Inkscape to design mine, by the way. It’s open-source and vector based, working on .svg and then creating PNG, JPG or PDF output, as you prefer. I used ggplot2::ggsave(device = "png", bg = "transparent") on a lot of my plots to save them in a separate folder and then selected and imported a bunch of them and played around until it looked nice. I had just got my second dose of the COVID vaccine so that was the only intellectual effort I could do that day. ↩︎

The perks of open-source and GitHub repositories! ↩︎

Mariana Montes

Doctor in linguistics.

My research interests include cognitive and corpus semantics and visual analytics.

  • Making of glossr
  • Academic writing in R Markdown I
  • All of my selves
  • Writing functions
  • Obsidian and Zotero

Writing your thesis

Bernhard bieri.

{iheiddown} ’s primary feature is to enable students of the Institute to write their thesis in R-Markdown. It takes care of the annoying formatting process and automates the most repetitive tasks a student faces when writing scholarly documents. In short, {iheiddown} allows its users to focus on the content rather than the formatting of a thesis.

This guide will show you how to get up and running and start writing your thesis in R while providing you with helpful tips and tricks to make you familiar with the workflow of writing your very own scholarly documents in R.

Installation

The installation process is the same than for the thesis template. You’ll need the following software:

  • Install R and R-Studio
  • For Windows
  • Install {iheiddown} by typing the following command install.packages("iheiddown") in the R-Studio console.

Note: typing remotes::install_github("jhollway/iheiddown") will provide you with the latest version from GitHub.

Create your first thesis project

Creating your first thesis is easy! Let’s look at how it is done. Before we begin, we have to create a new R project by clicking on the file tab in the top of the RStudio window and following the instructions of the prompt that appears. Now that we have created an R project for our presentation, we can open a new R-Markdown file. To do this click on the “plus file” logo in the top left corner and then on “R-Markdown”.

Step 1: Open a project

After you have done this, a little pop-up helper will appear. The first thing we will do is to select the {iheiddown} template for our thesis. To do so, click on the “From Template” option on the left and select the “Thesis {iheiddown}” template. Now give your thesis a name and click on “OK”.

Important note! Name your project index . This makes sure that the main Rmd file is called index.Rmd which is required to render your thesis with our {bookdown} based rendering function. Don’t worry though, you can rename the folder to your project name after creating it.

Step 2: Select a template

Congrats! You just created your first thesis project!

Hold on, this doesn’t look anything like a Word processor!? To see your thesis, you have to “knit” the code by clicking on the little “knit” button while viewing the 00-MyThesis.Rmd file. This will run all the code chunks in every chapter and convert the Markdown code to a correctly formatted PDF document that you will find in the \versions folder of your project.

Take a moment to read through the generated PDF to get acquainted with the {R-Markdown} syntax and to get a feel of the possibilities of {iheiddown} ’s thesis template. This first document is as much a tutorial as this vignette!

Edit your thesis

This section will focus on giving you an overview of the elements of an {iheiddown} thesis and give you a few tips and tricks to edit it.

The different elements of a {iheiddown} thesis

After this initial preview, let’s look at how the thesis project is structured to better understand how to edit it.

The index file

The index file contains two things: the YAML header and the preface of your thesis. It is also the backbone of your thesis in the sense that this is where you will want to knit your whole thesis from.

The YAML header is the place where the main options, metadata and formatting parameters are set. You can set the title of your presentation here, add your name, change the front matter of your thesis (abstract, acknowledgments, table of content, etc.).

The second element in this file is the preface. The only crucial thing to know here is that in order to create your package bibliography (the software you use to render your thesis) you need to leave the first code chunk there.

The chapters

The chapters contain the meat of your thesis, this is where you will outline your idea, run your analyses and draw your conclusions.

Chapters are structured in a similar way, so let us open the 01-introduction.Rmd chapter. In it, you will first find a YAML header that where you can set various chapter level metadata and options.

Note that if for some reason you rename the chapter, you will need to specify the new name in the YAML header too under the input option. Once you have done this you can write away!

The last thing to know about individual chapters is that you can knit them individually. This comes in handy when you want to generate only one part of your thesis for preview purposes.

The appendix and the references files

These files are a bit special as you might notice when you open them.

The 99-references.Rmd file generates the bibliography. This happens automatically, so you will most likely not need to alter this file. Just know that you can set the title of the reference section in the first line.

The 98-appendix.Rmd file allows you to showcase code, additional outputs and more in a separate section to avoid unnecessarily cluttering the main body of your thesis. This can be done by referencing code chunks from your main body and printing the computations you did in your R chunks or by adding new ones.

The _bookdown.yml file

The _bookdown.yml file contains additional information for the YAML header of the main .Rmd file. A standard user should not have to edit it. If for some reason or another you still feel like it, you need to know that you can set additional .Rmd subdirectories, set another output file than the standard \versions file, and toggle the deletion of merged files after the knitting process ended here.

The \bib folder

The bibliography folder contains two files; packages.bib and references.bib . The former is automatically generated by the first code chunk in the index.Rmd file and cites the packages you have loaded when running your code chunks. You will not need to alter this.

On the other hand, the references.bib file is the place to dump the bibtex citations that you will cite in your thesis.

The \data folder

The data folder is the place to put all the data that you use in the code chunk of your analysis. Remember to keep it tidy so you can easily link data to outputs down the line such as graphs and tables.

The \figures folder

The figures folder will contain all the graphical elements that you may want to include in your thesis e.g. figures, graphs, or images. It also contains a file named SecretariatDocument.pdf that you will need to replace with the one that was handed to you by the PhD or Master’s secretariat. Remember to rename the file you got from the secretariat as SecretariatDocument.pdf . Otherwise {iheiddown} will not recognize it.

The \front-matter folder

The front matter folder contains the front matter of your thesis. This is where you will be able to edit the abbreviations part in the corresponding Latex file, the acknowledgments section or the abstract of your thesis in their respective .Rmd files.

The \versions folder

This is where you will find the pdf file after your thesis has been knitted by {iheiddown} .

Additional resources

Here is a list of additional links that will help you get familiar with our {iheiddown} thesis template, {bookdown} and Markdown syntax.

  • R-Markdown Cookbook
  • Bookdown book
  • Markdown guide

BioST@TS homepage

Enough Markdown to Write a Thesis

Richard J Telford

September 6, 2023

1 Introduction

The traditional way to write a report, manuscript or thesis is to run the analyses in R or some other software and then copy the figures, tables etc. into a word processor. Then you find an error in the code or data and need to repeat the process. Repeatedly.

This is very inefficient and error prone: there is a better way.

Quarto lets you have the code and the text in one document. If the code or the data are updated, new versions of the figures and tables are automatically generated and inserted into the corrected document. This is a much more reproducible process.

This book is written with Quarto.

Perkel (2022) Cut the tyranny of copy-and-paste with these coding tools, Nature 603, 191-192 doi: https://doi.org/10.1038/d41586-022-00563-z

1.1 Organisation of this book

First Steps with Quarto shows you how to create a quarto document, edit it, add figures and tables, and render it as a finished document.

Towards a Thesis shows you how author a manuscript, report or thesis in quarto by adding citations and cross-references to figures and tables.

Fixing Problems The final section has some trouble shooting suggestions.

Quarto is based on R markdown. If you know how to use R markdown, you know how to use quarto as almost any R markdown document should also work with quarto.

There are several improvements in quarto over R markdown which make it easier to use.

No need to remember different behaviour and capabilities of rmarkdown vs bookdown etc.

Simplified cross-references

Better support for multiple programming languages

You will need to have installed

  • RStudio (version 2022.2 or newer)
  • quarto R package ( install.packages("quarto") )

If you cannot install quarto on your computer (perhaps because of permission problems), either use the Rmarkdown tutorial , or use posit.cloud .

Source Code

IMAGES

  1. 50 Expert Tips: Master Writing a Research Article in R Markdown

    writing thesis in r markdown

  2. Getting Started with R Markdown

    writing thesis in r markdown

  3. Writing a research paper in R Markdown

    writing thesis in r markdown

  4. R Markdown integration in the RStudio IDE

    writing thesis in r markdown

  5. What are your recommendations for thesis writing with RStudio and

    writing thesis in r markdown

  6. An updated R Markdown thesis template using the bookdown package

    writing thesis in r markdown

VIDEO

  1. Thesis in 3 Weeks: Day 12

  2. How to convert Markdown to Mind Map

  3. PhD

  4. 20 Essential Tips for a Successful PhD thesis by Cleo

  5. R Markdown Tutorial: Create R Markdown Files

  6. R Markdown: Table of Contents

COMMENTS

  1. An updated R Markdown thesis template using the bookdown package

    There are two options for doing so. 3a) RECOMMENDED Create a new RStudio project with a {thesisdown} template. In RStudio, click on File > New Project > New Directory. Then select Thesis Project using thesisdown from the dropdown that will look something like the image below. You'll see the graduation cap as the icon on the left for the ...

  2. Writing Your Dissertation (or Thesis) in RMarkdown

    Writing Your Dissertation (or Thesis) in RMarkdown ... probably the biggest hang up for most individuals that are interested in using RMarkdown with a PI that doesn't use Markdown, Latex or R. Conclusions. This was a quick introduction to how I wrote my dissertation using RMarkdown. I hope it was helpful to at least get started on the road to ...

  3. Writing a Master's thesis with R Markdown and Bookdown

    July 15, 2020. Citation. Bacher, 2020. I finished my Master's thesis very recently, and I wrote it with R Markdown, and more precisely with the bookdown package. It was really comfortable to do absolutely everything with R: data treatment, use of econometric methods, redaction with chunk of codes, and even the slides for the presentation!

  4. Welcome

    This R Markdown template is for writing an Oxford University thesis. The template is built using Yihui Xie's bookdown package, with heavy inspiration from Chester Ismay's thesisdown and the OxThesis template (most recently adapted by John McManigle). This template's sample content include illustrations of how to write a thesis in R ...

  5. Write your dissertation in Rmarkdown

    In between the \begin {centring} and \end {centring} we are going to specify a 3 cm spacing from the top of the page, to then insert the first element: the university logo. Undearneath the vertical spacing (vspace) function, add a new code chunk by selecting on the icon "insert" and clicking on "R". Inside it, write.

  6. Introduction

    Welcome to oxforddown ( Lyngs, 2019), a thesis template for R Markdown that I created when writing my own PhD thesis at the University of Oxford. This template allows you to write in R Markdown, while formatting the PDF output with the beautiful and time-tested OxThesis LaTeX template . The sample content is partly adapted from thesisdown .

  7. Writing your manuscript in R Markdown · Jeremy Hemberger

    As far as why to chose RMarkdown, R and RStudio have all of the tools and packages you need to make the setup and transition to writing in markdown easy. The workflow. Every time I start a new project in R, I do so in a skeleton directory that contains standardized folders to keep my business organized. An ongoing project looks something like this:

  8. GitHub

    UOAdown. This project provides a template for the writing of theses and dissertations in R markdown, and it automatically renders them formatted according to the University of Auckland Guidelines.This project was inspired by the thesisdown package.. Currently, the PDF and gitbook versions are fully-functional.

  9. An updated R Markdown thesis template using the bookdown package

    macdown. This project is inspired by the {bookdown} and {thesisdown} packages, adapted to provide a template for writing a McMaster graduate thesis in R markdown. The PDF uses McMaster Graduate Thesis LaTeX template. Under the hood, the McMaster Graduate Thesis LaTeX template is used to ensure that documents conform precisely to submission ...

  10. Writing your thesis

    Writing your thesis Bernhard Bieri 2022-11-09 {iheiddown}'s primary feature is to enable students of the Institute to write their thesis in R-Markdown.It takes care of the annoying formatting process and automates the most repetitive tasks a student faces when writing scholarly documents.

  11. Academic writing in R Markdown I

    The first step is, of course, to install R markdown. Assuming you already have R and R Studio, you run on the console: install.pacakges( "rmarkdown" ) # if you want Latex output: install.packages( "tinytex" ) tinytex::install_tinytex() Create new R Markdown file in R Studio. The second step is to create an empty document.

  12. Tips on Writing Thesis in RMarkdown

    Tips on Writing Thesis in RMarkdown Kaining Zhou 14 February, 2022. 1. To live preview the output without kniting the file. ... In Mendeley, check the citation key of the paper you want to cite (in the Document Details tab). In your R Markdown document, write the citation key in square brackets, for example [@Author2000]. 9. Debug when fail to ...

  13. GitHub

    To use {thesisdown} from RStudio: Ensure that you have already installed LaTeX and the fonts described above, and are using the latest version of RStudio.You can use thesisdown without RStudio. For example, you can write the Rmd files in your favorite text editor (e.g. Atom, Notepad++).But RStudio is probably the easiest tool for writing both R code and text in your thesis.

  14. Data, Code & Coffee

    I found writing in Markdown really satisfying. Writing a thesis can certainly be a little dull at times, but there were always new things to learn while using Markdown, and this certainly helped keep me motivated when writing wasn't going so well… Potential downsides Comments. This was the only major issue I faced using Markdown. While my ...

  15. GitHub

    This project provides a template for writing a PhD thesis in R Markdown, and rendering those files into a PDF formatted according to the requirements of the University of Washington.It uses the University of Washington Thesis class to convert R Markdown files into a PDF formatted ready for submission at UW. This project was inspired by the thesisdown and bookdown packages.

  16. GitHub

    A template for writing an Oxford University thesis in R Markdown. The template uses the bookdown R package together with the OxThesis LaTeX template, plus lots of inspiration from thesisdown. Sample PDF output; Sample BS4 book output; Examples of theses written with oxforddown (see also Google Scholar):

  17. Enough R to write a thesis

    Learn how to write reproducible documents (anything from a course assignment to a thesis or manuscript) in quarto: no more copy-paste nightmares. Quarto is the successor to R markdown (our earlier R markdown book is here). All the biostats books were written in R markdown or quarto; you can see the source code in our repo on GitHub.

  18. Chapter 5 Formatting

    Chapter 5. Formatting. The greatest strength of the Markdown language is that its simplicity makes it very easy to read and write even to newcomers. This is its key design principle, as outlined by the creator of the original Markdown language: A Markdown-formatted document should be publishable as-is, as plain text, without looking like it's ...

  19. Writing a Master's thesis with R Markdown and Bookdown

    LaTeX packages and commands. In preamble.tex, I put all the LaTeX commands, many of them being \usepackage.For example, the R package kableExtra provides a list of LaTeX packages required to be able to customize the tables (see here).. Here's a small list of the commands I used for my thesis. \renewcommand{\baselinestretch}{1.3} to change the space between lines;

  20. Writing Your Thesis in R Markdown

    Writing Your Thesis in R Markdown. Another option is to write your thesis using R Markdown. This might be particularly useful for you if you plan on using a number of R features in your thesis and would like to be able to change your code without having to completely update your old thesis document.

  21. Academic Writing in R Markdown II

    Here you must distinguish between the title of your chapter and the name of the file. For example, Chapters 2, 3 and 4 of my dissertation are called "From corpora to clouds", "Visualization tools" and "Case studies", but the files are called "workflow", "nephovis" and "dataset" respectively, with .Rmd extension in the R ...

  22. The Comprehensive R Archive Network

    We would like to show you a description here but the site won't allow us.

  23. Enough Markdown to Write a Thesis

    1.1 Organisation of this book. First Steps with Quarto shows you how to create a quarto document, edit it, add figures and tables, and render it as a finished document.. Towards a Thesis shows you how author a manuscript, report or thesis in quarto by adding citations and cross-references to figures and tables.. Fixing Problems The final section has some trouble shooting suggestions.