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!

College/University Repository Based on
American University
Brock University
École Doctorale de Mathématiques Hadamard
Drexel University
Duke University
Graduate Institute of International and Development Studies
Heidelberg University, Faculty of Biosciences
Humboldt University of Berlin
Kansas State University
Massachusetts Institute of Technology
Oregon State University
Oxford University
Smith College
Southampton University
Stanford University
Universidade Federal do Rio de Janeiro
Université Paris-Saclay
University College London
University of Arizona
University of California, Davis
University of California, Santa Barbara
University of Florida
University of Freiburg
University of Kansas
University of Manchester
University of Minnesota
University of New South Wales
University of Salzburg
University of Toronto
University of Washington
TU Wien
University of Bristol
Universidade Federal de Santa Catarina
Universiteit van Amsterdam

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.

thesis template 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.

thesis template 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 :

thesis template 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

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

ismayc/thesisdown An updated R Markdown thesis template using the bookdown package

  • thesisdown: thesisdown: A package for creating undergraduate, Masters,...
  • thesis_epub: Creates an R Markdown epub Thesis document
  • thesis_gitbook: Creates an R Markdown gitbook Thesis document
  • thesis_pdf: Creates an R Markdown PDF Thesis document
  • thesis_word: Creates an R Markdown Word Thesis document
  • Browse all...

ismayc/thesisdown: An updated R Markdown thesis template using the bookdown package

Using the bookdown package and LaTeX and Word thesis templates from Reed College, this package aims to encourage reproducible research using simple Markdown syntax while embedding all of the R code to produce plots and analyses as well.

Getting started

Browse package contents.

MaintainerChester Ismay <[email protected]>
LicenseMIT + file LICENSE
Version0.2.0.9000
Package repository
Installation Install the latest version of this package by entering the following in R:

R Package Documentation

Browse r packages, we want your feedback.

thesis template r markdown

Add the following code to your website.

REMOVE THIS Copy to clipboard

For more information on customizing the embed code, read Embedding Snippets .

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} .

Oxforddown: an Oxford University Thesis Template for R Markdown Abstract

Oxforddown: an Oxford University Thesis Template for R Markdown Abstract

oxforddown: An Oxford University Thesis Template for R Markdown

Author Name Your College University of Oxford

A thesis submitted for the degree of Doctor of Philosophy

Michaelmas 2018 For Yihui Xie Acknowledgements

This is where you will normally thank your advisor, colleagues, family and friends, as well as funding and institutional support. In our case, we will give our praises to the people who developed the ideas and tools that allow us to push open science a little step forward by writing plain-text, transparent, and reproducible theses in R Markdown. We must be grateful to John Gruber for inventing the original version of Markdown, to John MacFarlane for creating Pandoc (http://pandoc.org) which converts Markdown to a large number of output formats, and to Yihui Xie for creating knitr which introduced R Markdown as a way of embedding code in Markdown documents, and bookdown which added tools for technical and longer-form writing. Special thanks to Chester Ismay, who created the thesisdown package that helped many a PhD student write their theses in R Markdown. And a very special thanks to John McManigle, whose adaption of Sam Evans’ adaptation of Keith Gillow’s original maths template for writing an Oxford University DPhil thesis in LaTeX provided the template that I in turn adapted for R Markdown. Finally, profuse thanks to JJ Allaire, the founder and CEO of RStudio, and Hadley Wickham, the mastermind of the tidyverse without whom we’d all just given up and done data science in Python instead. Thanks for making data science easier, more accessible, and more fun for us all.

Ulrik Lyngs Linacre College, Oxford 2 December 2018 Abstract

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 LATEX template (most recently adapted by John McManigle). This template’s sample content include illustrations of how to write a thesis in R Markdown, and largely follows the structure from this R Markdown workshop. Congratulations for taking a step further into the lands of open, reproducible science by writing your thesis using a tool that allows you to transparently include ta- bles and dynamically generated plots directly from the underlying data. Hip hooray! Contents

List of Figures vii

List of Tables viii

List of Abbreviations ix

Introduction1 Why use it? ...... 1 Who should use it? ...... 2

1 How to use3 1.1 How oxforddown is structured ...... 3 1.2 Building your entire thesis ...... 7 1.3 Building a single chapter ...... 9

2 R Markdown basics 10 2.1 Basic markdown syntax ...... 11 2.2 Executable code chunks ...... 15 2.3 Executable inline code ...... 20 2.4 Executable code in other languages than R ...... 21

3 Citations, cross-references, and collaboration 22 3.1 Citations ...... 22 3.2 Cross-referencing ...... 25 3.3 Collaborative writing ...... 28 3.4 Additional resources ...... 29

4 Tables 30 4.1 Making LaTeX tables play nice ...... 30

5 Customisations and extensions 44 5.1 Front matter ...... 45 5.2 Shorten running header (PDF) ...... 46 5.3 Unnumbered chapters ...... 46 5.4 Beginning chapters with quotes (PDF) ...... 46 5.5 Highlighting corrections (HTML & PDF) ...... 47 5.6 Apply custom font color and highlighting to text (HTML & PDF) . 48 5.7 Including another paper in your thesis - embed a PDF document . . 49 5.8 Including another paper in your thesis - R Markdown child document 53 5.9 Customizing referencing ...... 57 5.10 Customizing the page headers and footers (PDF) ...... 59 5.11 Diving in to the OxThesis LaTeX template (PDF) ...... 60 5.12 Customising to a different university ...... 60

6 Troubleshooting 62 6.1 Error: Failed to build the bibliography via biber ...... 62

Conclusion 64 More info ...... 64

A The First Appendix 66

B The Second Appendix, for Fun 67

Works Cited 68

vi List of Figures

2.1 Code chunk syntax ...... 15 2.2 Oxford logo ...... 17 2.3 Oxford logo, rotated ...... 18 2.4 A ggplot of car stuff ...... 18 2.5 An Oxford logo that LaTeX will try to place at this position in the text 20

3.1 The ‘citr‘ add-in ...... 25 3.2 A marvel-lous meme ...... 27

4.1 Font sizes in LaTeX ...... 41

vii List of Tables

2.1 A knitr kable table ...... 19

3.1 Stopping cars ...... 27

viii List of Abbreviations

1-D, 2-D ... One- or two-dimensional, referring in this thesis to spatial dimensions in an image. Otter ..... One of the finest of water mammals. Hedgehog ... Quite a nice prickly friend.

ix 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.

1 Introduction

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.

2 1 How to use

1.1 How oxforddown is structured ...... 3 1.1.1 index.Rmd: metadata and layout options ...... 4 1.1.2 other .Rmd files in root folder: thesis chapters .5 1.1.3 front-and-back-matter/ ...... 5 1.1.4 _bookdown.yml: build options ...... 6 1.1.5 scripts-and-filters ...... 6 1.1.6 templates ...... 7 1.2 Building your entire thesis ...... 7 1.3 Building a single chapter ...... 9

1.1 How oxforddown is structured

. +-- index.Rmd +-- _bookdown.yml +-- 00-introduction.Rmd | ... +-- 07-conclusion.Rmd +-- front-and-back-matter | +-- _abstract.Rmd | +-- 98-appendices.Rmd | ...

3 1. How to use

+-- bibliography | +-- references.bib | ... +-- figures | ... +-- docs | +-- _main.pdf | ... +-- scripts_and_filters | +-- knit-functions.R | ... +-- templates | +-- template.tex | ...

1.1.1 index.Rmd: metadata and layout options

In index.Rmd, set your thesis’ basic metadata (e.g., title, author name) title: | `oxforddown`:\ An Oxford University Thesis \ Template for R Markdown author: Author Name college: Your College

Also set filepath(s) to your abstract, acknowledgements, abbreviations, and bibliography (one or more .bib files): abstract: | `r paste(readLines("front-and-back-matter/_abstract.Rmd"), ,→ collapse = '\n ')` acknowledgements: | `r paste(readLines("front-and-back-matter/_acknowledgements.Rmd"), ,→ collapse = '\n ')` dedication: For Yihui Xie abbreviations: | `r paste(readLines("front-and-back-matter/_abbreviations.Rmd"), ,→ collapse = '\n ')`

####################### ## bibliography path ##

4 1. How to use

####################### bibliography:[ bibliography/references.bib, ,→ bibliography/additional-references.bib]

Finally, index.Rmd is also where you customise layout options. For example, in PDF output what should the heading for the bibliography section say? How should page numbers be positioned? Should line numbers be shown? In HTML output, what CSS files should be used for styling?

### citation and bibliography style ### bibliography-heading-in-pdf: Works Cited ...

### position of page numbers ### ordinary-page-number-foot-or-head: foot #'foot' puts page number ,→ in footer, 'head' in header ordinary-page-number-position: C ... includeline-num: false #show line numbering in PDF? ...

bookdown::bs4_book: css: - templates/bs4_style.css - templates/corrections.css # remove to stop highlighting ,→ corrections

1.1.2 other .Rmd files in root folder: thesis chapters

• each chapter of your thesis should have its own .Rmd file in the root directory

• when you knit index.Rmd, these chapters are merged together in alphabetical

order, based on their filenames

1.1.3 front-and-back-matter/

• this folder holds the front and back matter of your thesis

5 1. How to use

• it has .Rmd files for your abstract, acknowledgements, abbreviations, and

a welcome note that is included in HTML output. Note how these files

start with an underscore (e.g. _abstract.Rmd). This means they will not

automatically be merged into the thesis – they are explicitly included in

• 98-appendices and 99-references.Rmd are automatically merged into

thesis, however - therefore their file names start with a high number, sothat

they will be included by the very end (merging is done alphabetically)

• 99-references.Rmd sole purpose is to set the heading for the references

section in HTML and Word output

1.1.4 _bookdown.yml: build options

• Set output directory for your thesis filesdocs/ ( is the default, as it makes it

easy to publish HTML output on GitHub pages)

• Should R Markdown automatically merge .Rmd files in alphabetical order?

Alternatively, specify explicitly which files should be included.

1.1.5 scripts-and-filters

• knit-function.R has the functions that are used when you build the entire

thesis by knitting index.Rmd

• create_chunk_options.R lets you include cute quotes at the start of a

chapter in PDF output

• colour_and_highlight.lua lets you color text or apply background color

6 1. How to use

1.1.6 templates

• template.tex is the LaTeX template used to build the entire thesis to PDF in the OxThesis layout (relies on ociamthesis.cls)

• brief-template.tex is the LaTeX template used to build a single chapter to PDF in the OxThesis layout (relies on ociamthesis.cls)

• beltcrest.pdf: the oxford logo used on the front page of the PDF output

1.2 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

PDF output knit: (function(input, ...) { thesis_formats <- "pdf"; ...

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 bythe 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)$"))

7 1. How to use within if ("pdf" %in% output_format){ is the one that removes files after PDF output is generated.

BS4 book output (HTML) knit: (function(input, ...) { thesis_formats <- "bs4"; ...

• 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 oxforddowns knitting function.

Gitbook output (HTML) knit: (function(input, ...) { thesis_formats <- "gitbook"; ...

• 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 oxforddowns knitting function.

Word output knit: (function(input, ...) { thesis_formats <- "word"; ...

• 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

8 1. How to use

requests that optimise the Word output, e.g. by using tools from the officer package.

1.3 Building a single chapter

To knit an individual chapter without compiling the entire thesis you:

1. open the .Rmd file of a chapter 2. 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) 3. 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.: output: bookdown::pdf_document2: template: templates/brief_template.tex citation_package: biblatex documentclass: book bibliography: references.bib

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

9 Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. . . There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain. . . — Cicero’s de Finibus Bonorum et Malorum. 2 R Markdown basics

Contents 2.1 Basic markdown syntax ...... 11 2.1.1 Whitespace ...... 11 2.1.2 Italics and bold ...... 11 2.1.3 Inline code ...... 11 2.1.4 Sub and superscript ...... 11 2.1.5 Strikethrough ...... 11 2.1.6 ‘Escaping’ (aka “What if I need an actual asterisk?”) . . 12 2.1.7 Endash (–), emdash (—) ...... 12 2.1.8 Blockquotes ...... 12 2.1.9 Headings ...... 12 2.1.10 Lists ...... 12 2.1.11 Line breaks ...... 13 2.1.12 Hyperlinks ...... 13 2.1.13 Footnotes ...... 14 2.1.14 Comments ...... 14 2.1.15 Math ...... 14 2.2 Executable code chunks ...... 15 2.2.1 Setup chunks - setup, images, plots ...... 16 2.2.2 Including images ...... 16 2.2.3 Including plots ...... 17 2.2.4 Including tables ...... 19 2.2.5 Control positioning ...... 19 2.3 Executable inline code ...... 20 2.4 Executable code in other languages than R ...... 21

Here is a brief introduction to using R Markdown. Markdown is a simple formatting

10 2. R Markdown basics syntax for authoring HTML, PDF, and MS Word documents and much, much more. R Markdown provides the flexibility of Markdown with the implemen- tation of R input and output. For more details on using R Markdown see http://rmarkdown.rstudio.com.

2.1 Basic markdown syntax

2.1.1 Whitespace

Be careful with your spacing. While whitespace largely is ignored, it does at times give markdown signals as to how to proceed. As a habit, try to keep everything left aligned whenever possible, especially as you type a new paragraph. In other words, there is no need to indent basic text in the Rmd document (in fact, it might cause your text to do funny things if you do).

2.1.2 Italics and bold

• Italics are done like *this* or _this_ • Bold is done like **this** or __this__ • Bold and italics is done like ***this***, ___this___, or (the most transparent solution, in my opinion) **_this_**

2.1.3 Inline code

• Inline code is created with backticks like `this`

2.1.4 Sub and superscript

2 Sub2 and super script is created like this~2~ and thisˆ2ˆ

2.1.5 Strikethrough

• Strikethrough is done ~~like this~~

11 2. R Markdown basics

2.1.6 ‘Escaping’ (aka “What if I need an actual asterisk?”)

• To include an actual *, _ or \, add another \ in front of them: \*, \_, \\

2.1.7 Endash (–), emdash (—)

• – and — with -- and ---

2.1.8 Blockquotes

Do like this:

Put a > in front of the line.

2.1.9 Headings

Section headers are created with #’s of increasing number, i.e.

• # First-level heading • ## Second-level heading • ### Etc.

In PDF output, a level-five heading will turn into a paragraph heading, i.e. \paragraph{My level-five heading}, which appears as bold text on the same line as the sub- sequent paragraph.

2.1.10 Lists

Unordered list by starting a line with an * or a -:

• Item 1 • Item 2

Ordered lists by starting a line with a number. Notice that you can mislabel the numbers and Markdown will still make the order right in the output:

12 2. R Markdown basics

To create a sublist, indent the values a bit (at least four spaces or a tab):

1. Item 1 2. Item 2 3. Item 3

• Item 3a • Item 3b

2.1.11 Line breaks

The official Markdown way to create line breaks is by ending a line with more than two spaces.

Roses are red. Violets are blue.

This appears on the same line in the output, because we didn’t add spaces after red.

This appears with a line break because I added spaces after red.

I find this is confusing, so I recommend the alternative way: Ending aline with a backslash will also create a linebreak:

To create a new paragraph, you put a blank line.

Therefore, this line starts its own paragraph.

2.1.12 Hyperlinks

• This is a hyperlink created by writing the text you want turned into a clickable link in [square brackets followed by a](https://hyperlink-in-parentheses)

13 2. R Markdown basics

2.1.13 Footnotes

• Are created1 by writing either ˆ[my footnote text] for supplying the foot- note content inline, or something like [ˆa-random-footnote-label] and supplying the text elsewhere in the format shown below 2:

[ˆa-random-footnote-label]: This is a random test.

2.1.14 Comments

To write comments within your text that won’t actually be included in the output, use the same syntax as for writing comments in HTML. That is, .

2.1.15 Math

The syntax for writing math is stolen from LaTeX. To write a math expression that will be shown inline, enclose it in dollar signs. - This: $A = \pi*rˆ{2}$ Becomes: A = π ∗ r2

To write a math expression that will be shown in a block, enclose it in two dollar signs. This: $$A = \pi*rˆ{2}$$

To create numbered equations, put them in an ‘equation’ environment and give them a label with the syntax (\#eq:label), like this:

\begin{equation} f\left(k\right) = \binom{n}{k} pˆk\left(1-p\right)ˆ{n-k} (\#eq:binom) \end{equation}

1my footnote text 2This is a random test.

14 2. R Markdown basics

Becomes: n! f (k) = pk (1 − p)n−k (2.1) k For more (e.g. how to theorems), see e.g. the documentation on bookdown.org

2.2 Executable code chunks

The magic of R Markdown is that we can add executable code within our document to make it dynamic. We do this either as code chunks (generally used for loading libraries and data, performing calculations, and adding images, plots, and tables), or inline code (generally used for dynamically reporting results within our text). The syntax of a code chunk is shown in Figure 2.1.

Figure 2.1: Code chunk syntax

Common chunk options include (see e.g. bookdown.org):

• echo: whether or not to display code in knitted output • eval: whether or to to run the code in the chunk when knitting • include: whether to include anything from the from a code chunk in the output document • fig.cap: figure caption • fig.scap: short figure caption, which will be used in the ‘List of Figures’in the PDF front matter

15 2. R Markdown basics

IMPORTANT: Do not use underscoores in your chunk labels - if you do, you are likely to get an error in PDF output saying something like “! Package caption Error: \caption outside float”.

2.2.1 Setup chunks - setup, images, plots

An R Markdown document usually begins with a chunk that is used to load libraries, and to set default chunk options with knitr::opts_chunk$set. In your thesis, this will probably happen in index.Rmd and/or as opening chunks in each of your chapters.

```{r setup, include=FALSE} # don't show code unless we explicitly set echo = TRUE knitr::opts_chunk$set(echo = FALSE) library(tidyverse) ```

2.2.2 Including images

Code chunks are also used for including images, with include_graphics from the knitr package, as in Figure 2.2 knitr::include_graphics("figures/sample-content/beltcrest.png")

Useful chunk options for figures include:

• out.width (use with a percentage) for setting the image size • if you’ve got an image that gets waaay to big in your output, it will be constrained to the page width by setting out.width = "100%"

Figure rotation You can use the chunk option out.extra to rotate images. The syntax is different for LaTeX and HTML, so for ease we might start byas- signing the right string to a variable that depends on the format you’re outputting to:

16 2. R Markdown basics

Figure 2.2: Oxford logo

if (knitr::is_latex_output()){ rotate180 <- "angle=180" } else { rotate180 <- "style='transform:rotate(180deg);'" }

Then you can reference that variable as the value of out.extra to rotate images, as in Figure 2.3.

2.2.3 Including plots

Similarly, code chunks are used for including dynamically generated plots. You use ordinary code in R or other languages - Figure 2.4 shows a plot of the cars dataset of stopping distances for cars at various speeds (this dataset is built in to R). cars %>% ggplot()+ aes(x = speed,y= dist)+ geom_point()

Under the hood, plots are included in your document in the same way as images

17 2. R Markdown basics

Figure 2.3: Oxford logo, rotated

0 5 10 15 20 25 speed

Figure 2.4: A ggplot of car stuff

18 2. R Markdown basics

Table 2.1: A knitr kable table

speed dist 4 2 4 10 7 4 7 22 8 16 9 10

- when you build the book or knit a chapter, the plot is automatically generated from your code, saved as an image, then included into the output document.

2.2.4 Including tables

Tables are usually included with the kable function from the knitr package.

Table 2.1 shows the first rows of that cars data - read in your own data, then use this approach to automatically generate tables. cars %>% head() %>% knitr::kable(caption = "A knitr kable table")

• Gotcha: when using kable, captions are set inside the kable function • The kable package is often used with the kableExtra package

2.2.5 Control positioning

One thing that may be annoying is the way R Markdown handles “floats” like tables and figures. In your PDF output, LaTeX will try to find the bestplaceto put your object based on the text around it and until you’re really, truly done writing you should just leave it where it lies.

In general, you should allow LaTeX to do this, but if you really really need a figure to be positioned where you put in the document, then you can makeLaTeX attempt to do this with the chunk option fig.pos="H", as in Figure 2.5:

19 2. R Markdown basics knitr::include_graphics("figures/sample-content/beltcrest.png")

Figure 2.5: An Oxford logo that LaTeX will try to place at this position in the text

As anyone who has tried to manually play around with the placement of figures in a Word document knows, this can have lots of side effects with extra spacing on other pages, etc. Therefore, it is not generally a good idea to do this - only do it when you really need to ensure that an image follows directly under text where you refer to it (in this document, I needed to do this for Figure 4.1 in section 4.1.4). For more details, read the relevant section of the R Markdown Cookbook.

2.3 Executable inline code

‘Inline code’ simply means inclusion of code inside text. The syntax for doing this is `r R_CODE` For example, `r 4 + 4` will output 8 in your text. You will usually use this in parts of your thesis where you report results - read in data or results in a code chunk, store things you want to report in a variable, then insert the value of that variable in your text. For example, we might assign the number of rows in the cars dataset to a variable:

20 2. R Markdown basics num_car_observations <- nrow(cars)

We might then write: “In the cars dataset, we have `r num_car_observations` observations.” Which would output: “In the cars dataset, we have 50 observations.”

2.4 Executable code in other languages than R

If you want to use other languages than R, such as Python, Julia C++, or SQL, see the relevant section of the R Markdown Cookbook

21 3 Citations, cross-references, and collaboration

3.1 Citations ...... 22 3.1.1 PDF output ...... 23 3.1.2 Gitbook output ...... 24 3.1.3 Insert references easily with the citr add-in ...... 25 3.2 Cross-referencing ...... 25 3.2.1 Section references ...... 25 3.2.2 Figure (image and plot) references ...... 26 3.2.3 Table references ...... 26 3.2.4 Including page numbers ...... 27 3.3 Collaborative writing ...... 28 3.4 Additional resources ...... 29

3.1 Citations

The usual way to include citations in an R Markdown document is to put references in a plain text file with the extension .bib, in BibTex format.1 Then reference the path to this file in index.Rmd’s YAML header with bibliography: example.bib.

1The bibliography can be in other formats as well, including EndNote (.enl) and RIS (.ris), see rmarkdown.rstudio.com/authoring_bibliographies_and_citations.

22 3. Citations and cross-refs

Most reference managers can create a .bib file with you references automatically. However, the by far best reference manager to use with R Markdown is Zotero with the Better BibTex plug-in, because the citr plugin for RStudio (see below) can read references directly from your Zotero library!

Here is an example of an entry in a .bib file:

@article{Shea2014, author = {Shea, Nicholas and Boldt, Annika}, journal = {Trends in Cognitive Sciences}, pages = {186--193}, title = {{Supra-personal cognitive control}}, volume = {18}, year = {2014}, doi = {10.1016/j.tics.2014.01.006}, }

In this entry highlighed section, ‘Shea2014’ is the citation identifier. To default way to cite an entry in your text is with this syntax: [@citation-identifier]. So I might cite some things (Shea et al. 2014; Lottridge et al. 2012).

3.1.1 PDF output

In PDF output, the bibliography is handled by the OxThesis LaTeX template. If you set bib-humanities: true in index.Rmd, then in-text references will be formatted as author-year; otherwise references will be shown as numbers.

If you choose author-year formatting, a number of variations on the citation syntax are useful to know:

• Put author names outside the parenthesis

– This: @Shea2014 says blah. – Becomes: Shea et al. (2014) says blah.

• Include only the citation-year (in parenthesis)

– This: Shea et al. says blah [-@Shea2014] – Becomes: Shea et al. says blah (2014)

23 3. Citations and cross-refs

• Add text and page or chapter references to the citation

– This: [see @Shea2014, pp. 33-35; also @Wu2016, ch. 1] – Becomes: Blah blah (see Shea et al. 2014, pp. 33-35; also Wu 2016, ch. 1).

3.1.2 Gitbook output

In gitbook output, citations are by default inserted in the Chicago author-date for- mat.

To change the format, add csl: some-other-style.csl in index.Rmd’s YAML header. You can browse through and download styles at zotero.org/styles.

24 3. Citations and cross-refs

Figure 3.1: The ‘citr‘ add-in

3.1.3 Insert references easily with the citr add-in

For an easy way to insert citations, try the citr RStudio add-in (Figure 3.1). You can install this add-in by typing install.packages("citr") in the R Console.

3.2 Cross-referencing

We can make cross-references to sections within our document, as well as to figures (images and plots) and tables.

The general cross-referencing syntax is \@ref(label)

3.2.1 Section references

Headers are automatically assigned a reference label, which is the text in lower caps separated by dashes. For example, # My header is automatically given the label my-header. So # My header can be referenced with \@ref(my-section)

25 3. Citations and cross-refs

Remember what we wrote in section 3.1?

We can also use hyperlink syntax and add # before the label, though this is only guaranteed to work properly in HTML output:

• So if we write Remember what we wrote up in [the previous section](#citations)? • It becomes Remember what we wrote up in the previous section?

Creating custom labels

It is a very good idea to create custom labels for our sections. This is because the automatically assigned labels will change when we change the titles of the sections - to avoid this, we can create the labels ourselves and leave them untouched if we change the section titles.

We create custom labels by adding {#label} after a header, e.g. # My section {#my-label}. See our chapter title for an example. That was section3.

3.2.2 Figure (image and plot) references

• To refer to figures (i.e. images and plots) use the syntax \@ref(fig:label) • GOTCHA: Figures and tables must have captions if you wish to cross- reference them.

Let’s add an image: knitr::include_graphics("figures/sample-content/captain.jpeg")

We refer to this image with \@ref(fig:captain). So Figure 3.2 is this image.

And in Figure 2.4 we saw a cars plot.

3.2.3 Table references

• To refer to tables use the syntax \@ref(tab:label)

Let’s include a table:

26 3. Citations and cross-refs

Figure 3.2: A marvel-lous meme

Table 3.1: Stopping cars

speed dist 4 2 4 10 7 4 7 22 8 16

knitr::kable(cars[1:5,], caption="Stopping cars")

We refer to this table with \@ref(tab:cars-table2). So Table 3.1 is this table.

And in Table 2.1 we saw more or less the same cars table.

3.2.4 Including page numbers

Finally, in the PDF output we might also want to include the page number of a reference, so that it’s easy to find in physical printed output. LaTeX hasa command for this, which looks like this: \pageref{fig/tab:label} (note: curly

27 3. Citations and cross-refs braces, not parentheses)

When we output to PDF, we can use raw LaTeX directly in our .Rmd files. So if we wanted to include the page of the cars plot we could write:

• This: Figure \@ref(fig:cars-plot) on page \pageref(fig:cars-plot) • Becomes: Figure 2.4 on page 18

Include page numbers only in PDF output

A problem here is that LaTeX commands don’t display in HTML output, so in the gitbook output we’d see simply “Figure 2.4 on page”.

One way to get around this is to use inline R code to insert the text, and use an ifelse statement to check the output format and then insert the appropriate text.

• So this: `r ifelse(knitr::is_latex_output(), "Figure \\@ref(fig:cars-plot) on page \\pageref{fig:cars-plot}", "")` • Inserts this (check this on both PDF and gitbook): Figure 2.4 on page 18

Note that we need to escape the backslash with another backslash here to get the correct output.

3.3 Collaborative writing

Best practices for collaboration and change tracking when using R Markdown are still an open question. In the blog post One year to dissertate by Lucy D’Agostino, which I highly recommend, the author notes that she knits .Rmd files to a word document, then uses the googledrive R package to send this to Google Drive for comments / revisions from co-authors, then incorporates Google Drive suggestions by hand into the .Rmd source files. This is a bit clunky, and there are ongoing discussions among the R Markdown developers about what the best way is to handle collaborative writing (see issue #1463 on GitHub, where CriticMarkup is among the suggestions).

28 3. Citations and cross-refs

For now, this is an open question in the community of R Markdown users. I often knit to a format that can easily be imported to Google Docs for comments, then go over suggested revisions and manually incorporate them back in to the .Rmd source files. For articles, I sometimes upload a near-final draftto Overleaf, then collaboratively make final edits to the LaTeX file there. I suspect some great solution will be developed in the not-to-distant future, probably by the RStudio team.

3.4 Additional resources

• R Markdown: The Definitive Guide - https://bookdown.org/yihui/rmarkdown/

• R for Data Science - https://r4ds.had.co.nz

29 4 Tables

4.1 Making LaTeX tables play nice ...... 30 4.1.1 Making your table pretty ...... 30 4.1.2 If your table is too wide ...... 31 4.1.3 If your table is too long ...... 32 4.1.4 Max power: manually adjust the raw LaTeX output . . 41

4.1 Making LaTeX tables play nice

Dealing with tables in LaTeX can be painful. This section explains the main tricks you need to make the pain go away.

(Note: if you are looking at the ebook version, you will not see much difference in this section, as it is only relevant for PDF output!)

4.1.1 Making your table pretty

When you use kable to create tables, you will almost certainly want to set the option booktabs = TRUE. This makes your table look a million times better:

30 4. Tables library(knitr) library(tidyverse) head(mtcars) %>% kable(booktabs = TRUE)

mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1

Compare this to the default style, which looks terrible: head(mtcars) %>% kable() mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1

4.1.2 If your table is too wide

You might find that your table expands into the margins of the page, like thetables above. Fix this with the kable_styling function from the kableExtra package: library(kableExtra) head(mtcars) %>% kable(booktabs = TRUE) %>% kable_styling(latex_options = "scale_down")

This scales down the table to fit the page width.

31 4. Tables

4.1.3 If your table is too long

If your table is too long to fit on a single page, set longtable = TRUE in the kable function to split the table across multiple pages. a_long_table % select(1:8) %>% kable(booktabs = TRUE, longtable = TRUE)

mpg cyl disp hp drat wt qsec vs Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1

32 4. Tables

Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 Mazda RX41 21.0 6 160.0 110 3.90 2.620 16.46 0 Mazda RX4 Wag1 21.0 6 160.0 110 3.90 2.875 17.02 0 Datsun 7101 22.8 4 108.0 93 3.85 2.320 18.61 1 Hornet 4 Drive1 21.4 6 258.0 110 3.08 3.215 19.44 1 Hornet Sportabout1 18.7 8 360.0 175 3.15 3.440 17.02 0 Valiant1 18.1 6 225.0 105 2.76 3.460 20.22 1 Duster 3601 14.3 8 360.0 245 3.21 3.570 15.84 0 Merc 240D1 24.4 4 146.7 62 3.69 3.190 20.00 1 Merc 2301 22.8 4 140.8 95 3.92 3.150 22.90 1 Merc 2801 19.2 6 167.6 123 3.92 3.440 18.30 1 Merc 280C1 17.8 6 167.6 123 3.92 3.440 18.90 1 Merc 450SE1 16.4 8 275.8 180 3.07 4.070 17.40 0 Merc 450SL1 17.3 8 275.8 180 3.07 3.730 17.60 0 Merc 450SLC1 15.2 8 275.8 180 3.07 3.780 18.00 0 Cadillac Fleetwood1 10.4 8 472.0 205 2.93 5.250 17.98 0 Lincoln Continental1 10.4 8 460.0 215 3.00 5.424 17.82 0 Chrysler Imperial1 14.7 8 440.0 230 3.23 5.345 17.42 0 Fiat 1281 32.4 4 78.7 66 4.08 2.200 19.47 1 Honda Civic1 30.4 4 75.7 52 4.93 1.615 18.52 1 Toyota Corolla1 33.9 4 71.1 65 4.22 1.835 19.90 1 Toyota Corona1 21.5 4 120.1 97 3.70 2.465 20.01 1 Dodge Challenger1 15.5 8 318.0 150 2.76 3.520 16.87 0 AMC Javelin1 15.2 8 304.0 150 3.15 3.435 17.30 0 Camaro Z281 13.3 8 350.0 245 3.73 3.840 15.41 0 Pontiac Firebird1 19.2 8 400.0 175 3.08 3.845 17.05 0 Fiat X1-91 27.3 4 79.0 66 4.08 1.935 18.90 1 Porsche 914-21 26.0 4 120.3 91 4.43 2.140 16.70 0 Lotus Europa1 30.4 4 95.1 113 3.77 1.513 16.90 1 Ford Pantera L1 15.8 8 351.0 264 4.22 3.170 14.50 0 Ferrari Dino1 19.7 6 145.0 175 3.62 2.770 15.50 0 Maserati Bora1 15.0 8 301.0 335 3.54 3.570 14.60 0

33 4. Tables

Volvo 142E1 21.4 4 121.0 109 4.11 2.780 18.60 1

When you do this, you’ll probably want to make the header repeat on new pages. Do this with the kable_styling function from kableExtra: a_long_table %>% kable(booktabs = TRUE, longtable = TRUE) %>% kable_styling(latex_options = "repeat_header")

mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3 Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3 Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3 Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4 Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4 Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2 AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2 Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4 Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2 Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4 Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6 Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8

34 4. Tables

(continued) mpg cyl disp hp drat wt qsec vs am gear carb Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2 Mazda RX41 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag1 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Datsun 7101 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive1 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout1 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 Valiant1 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 Duster 3601 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 Merc 240D1 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 Merc 2301 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 Merc 2801 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 Merc 280C1 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 Merc 450SE1 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3 Merc 450SL1 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3 Merc 450SLC1 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3 Cadillac Fleetwood1 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4 Lincoln Continental1 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 Chrysler Imperial1 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4 Fiat 1281 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Honda Civic1 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Toyota Corolla1 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corona1 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Dodge Challenger1 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2 AMC Javelin1 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2 Camaro Z281 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4 Pontiac Firebird1 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2 Fiat X1-91 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 Porsche 914-21 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 Lotus Europa1 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Ford Pantera L1 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4 Ferrari Dino1 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6 Maserati Bora1 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8 Volvo 142E1 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2

Unfortunately, we cannot use the scale_down option with a longtable. So if a longtable is too wide, you can either manually adjust the font size, or show the table in landscape layout. To adjust the font size, use kableExtra’s font_size option:

35 4. Tables a_long_table %>% kable(booktabs = TRUE, longtable = TRUE) %>% kable_styling(font_size =9, latex_options = "repeat_header")

mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3 Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3 Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3 Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4 Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4 Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2 AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2 Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4 Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2 Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4 Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6 Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8 Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2 Mazda RX41 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag1 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Datsun 7101 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive1 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout1 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 Valiant1 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 Duster 3601 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 Merc 240D1 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 Merc 2301 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 Merc 2801 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 Merc 280C1 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 Merc 450SE1 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3 Merc 450SL1 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3 Merc 450SLC1 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3 Cadillac Fleetwood1 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4

36 4. Tables

(continued) mpg cyl disp hp drat wt qsec vs am gear carb Lincoln Continental1 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 Chrysler Imperial1 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4 Fiat 1281 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Honda Civic1 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Toyota Corolla1 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corona1 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Dodge Challenger1 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2 AMC Javelin1 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2 Camaro Z281 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4 Pontiac Firebird1 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2 Fiat X1-91 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 Porsche 914-21 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 Lotus Europa1 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Ford Pantera L1 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4 Ferrari Dino1 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6 Maserati Bora1 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8 Volvo 142E1 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2

To put the table in landscape mode, use kableExtra’s landscape function: a_long_table %>% kable(booktabs = TRUE, longtable = TRUE) %>% kable_styling(latex_options = "repeat_header") %>% landscape()

37 4. Tables mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4Mazda RX4 WagDatsun 710Hornet 4 Drive 21.0Hornet Sportabout 21.0 6Valiant 6 18.7 160.0Duster 21.4 22.8 160.0 360 110 8Merc 110 240D 3.90 6 4 360.0 3.90Merc 2.875 230 258.0 108.0 175 2.620 17.02Merc 110 280 3.15 16.46 93 3.08 0 3.440Merc 3.85 280C 18.1 14.3 0 3.215 17.02 2.320Merc 1 450SE 24.4 19.44 6 8 18.61 1 0Merc 450SL 1 225.0 360.0 4 22.8 1Merc 4 450SLC 105 0 245 146.7 4 19.2Cadillac 0 Fleetwood 2.76 3.21 4 1 17.8 62 4 3.460 3.570 140.8 3 16.4 6Lincoln Continental 3.69 4 10.4 20.22 3 15.84 6 167.6 4Chrysler 17.3 95 3.190 Imperial 8 15.2 10.4 167.6 123 1 0 8 2 3.92 20.00Fiat 275.8 128 8 123 1 3.92 472.0 3.150 8 1 8Honda 180 1 0 0 275.8 Civic 3.92 3.440 14.7 205 22.90 275.8 460.0 3.07Toyota 180 Corolla 3.440 18.30 2.93 180 0 215 1 4.070 8 3.07 18.90 3 3 5.250 1 3.07Toyota 3.00 Corona 17.40 440.0 3.730 17.98 1 3.780 0 5.424Dodge 230 4 17.60 Challenger 0 0 18.00 1 4 17.82 30.4 0 33.9 3.23AMC 0 32.4 Javelin 0 4 5.345 0 0 0Camaro 2 4 21.5 Z28 4 0 15.5 4 17.42 4 0Pontiac 4 Firebird 0 0 75.7 71.1 4 2 3 8 0 78.7 3 4 120.1 318.0 52 65 3 15.2 4 66 3 0 3 150 4.93 4.22 3 97 19.2 4.08 4 13.3 2.76 8 1.615 1.835 3.70 3 2.200 3.520 3 304.0 3 8 18.52 19.90 4 2.465 19.47 8 16.87 150 400.0 20.01 1 1 350.0 1 175 3.15 0 4 245 1 3.435 3.08 1 1 3.73 1 17.30 3.845 0 0 3.840 17.05 0 4 4 15.41 4 3 0 3 0 0 2 1 0 1 2 0 1 3 3 3 2 2 4

38 4. Tables mpg cyl disp hp drat wt qsec vs am gear carb Fiat X1-9Porsche 914-2Lotus EuropaFord Pantera LFerrari Dino 26.0 27.3Maserati Bora 30.4 4 15.8Volvo 142E 4 120.3 4Mazda RX41 8 79.0 19.7 91Mazda 95.1 351.0 RX4 Wag1 15.0 4.43 66 113Datsun 264 6 7101 2.140 4.08 3.77 4.22 8 145.0 16.70 21.0 1.935Hornet 21.4 1.513 4 3.170 301.0 175 Drive1 21.0 18.90 16.90Hornet 0 14.50 335 Sportabout1 3.62 6 4 1Valiant1 6 3.54 1 2.770 160.0 0 121.0 18.7 1 22.8 160.0 3.570Duster 15.50 110 21.4 109 3601 1 110 1 14.60 1 3.90 8Merc 4.11 0 4 240D1 5 3.90 6 2.875 360.0 2.780 0 108.0 2.620 4Merc 258.0 17.02 5 175 1 2301 18.60 5 16.46 110 93Merc 2 1 3.15 2801 0 1 3.08 3.85 18.1 3.440 1 14.3 0Merc 2 5 280C1 4 3.215 2.320 17.02 1 24.4 5 1Merc 450SE1 6 19.44 8 18.61 1 0Merc 6 225.0 360.0 450SL1 4 1 1 4 4 8 22.8 105 245 146.7 4Merc 0 450SLC1 2.76 3.21 19.2 0 1 17.8 4Cadillac 62 Fleetwood1 4 3.460 3.570 2 16.4 140.8 3.69 4 3 6Lincoln 20.22 15.84 Continental1 6 10.4 3 4 17.3 3.190 167.6 8Chrysler 95 10.4 167.6 Imperial1 1 0 15.2 20.00 123 275.8 8 2 3.92 8 123 1 3.92 1 8 180 472.0 1 3.150 0 0 8 275.8 3.92 14.7 3.440 460.0 3.07 205 22.90 275.8 180 3.440 18.30 0 215 4.070 2.93 8 180 3.07 18.90 3 3 1 3.00 17.40 5.250 440.0 1 3.07 3.730 1 5.424 17.98 230 4 3.780 17.60 0 0 1 4 17.82 0 3.23 18.00 0 0 0 5.345 0 0 2 4 0 17.42 0 4 0 4 0 0 3 0 2 3 4 3 4 0 3 3 3 4 3 3 4 3 4 (continued)

39 4. Tables mpg cyl disp hp drat wt qsec vs am gear carb Fiat 1281Honda Civic1Toyota Corolla1Toyota Corona1Dodge Challenger1 30.4 33.9 32.4AMC Javelin1 21.5 15.5 4 4 4Camaro Z281 4 8Pontiac 75.7 71.1 78.7 Firebird1 120.1 318.0Fiat 15.2 X1-91 52 65 66 150 97Porsche 4.93 4.22 4.08 914-21 19.2 2.76 8 3.70 13.3Lotus 1.615 1.835 2.200 Europa1 3.520 304.0 2.465 8 18.52 19.90 19.47 16.87 150 8Ford 20.01 Pantera 400.0 L1 1 1 1 3.15 350.0 26.0 0Ferrari 175 Dino1 1 27.3 3.435 245 3.08 30.4Maserati 1 1 1 Bora1 17.30 4 0 3.73 0 3.845 4 15.8Volvo 120.3 142E1 3.840 4 0 17.05 4 4 79.0 4 15.41 3 8 91 3 95.1 0 19.7 0 15.0 351.0 0 4.43 66 113 2 1 1 264 2.140 4.08 6 0 2 3.77 1 8 0 3 4.22 16.70 1.935 145.0 21.4 1.513 301.0 3.170 18.90 175 16.90 0 3 335 4 14.50 3 3.62 2 1 3.54 1 121.0 2.770 1 0 3.570 2 109 15.50 1 4 1 14.60 4.11 1 5 0 2.780 0 4 5 18.60 1 5 2 1 1 1 2 5 4 5 1 6 4 8 2 (continued)

40 4. Tables

4.1.4 Max power: manually adjust the raw LaTeX output

For total flexibility, you can adjust the raw LaTeX output from kable/kableExtra that generates the table. Let us consider how we would do this for the example of adjusting the font size if our table is too wide: Latex has a bunch of standard commands that set an approximate font size, as shown below in Figure 4.1.

Figure 4.1: Font sizes in LaTeX

You could use these to manually adjust the font size in your longtable in two steps:

1. Wrap the longtable environment in, e.g., a scriptsize environment, by doing a string replacement in the output from kable/kableExtra 2. Add the attributes that make R Markdown understand that the table is a table (it seems R drops these when we do the string replacement) our_adjusted_table % kable(booktabs = TRUE, longtable = TRUE) %>% kable_styling(latex_options = "repeat_header") %>% # wrap the longtable in a tiny environment str_replace('\\\\begin\\{longtable\\}', '\\\\begin\\{scriptsize\\}\n\\\\begin\\{longtable\\}') ,→ %>% str_replace('\\\\end\\{longtable\\}', '\\\\end\\{longtable\\}\n\\\\end\\{scriptsize\\}')

#add attributes to make R Markdown treat this as a kable LaTeX ,→ table again

41 4. Tables our_adjusted_table %>% structure(format = " latex ", class = "knitr_kable")

mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3 Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3 Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3 Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4 Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4 Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2 AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2 Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4 Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2 Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4 Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6 Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8 Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2 Mazda RX41 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag1 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Datsun 7101 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive1 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout1 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 Valiant1 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 Duster 3601 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 Merc 240D1 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 Merc 2301 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 Merc 2801 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 Merc 280C1 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 Merc 450SE1 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3 Merc 450SL1 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3 Merc 450SLC1 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3 Cadillac Fleetwood1 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4 Lincoln Continental1 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 Chrysler Imperial1 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4 Fiat 1281 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Honda Civic1 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Toyota Corolla1 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corona1 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Dodge Challenger1 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2 AMC Javelin1 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2

42 4. Tables

(continued) mpg cyl disp hp drat wt qsec vs am gear carb

Camaro Z281 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4 Pontiac Firebird1 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2 Fiat X1-91 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 Porsche 914-21 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 Lotus Europa1 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Ford Pantera L1 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4 Ferrari Dino1 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6 Maserati Bora1 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8 Volvo 142E1 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2

43 There is grandeur in this view of life, with its several powers, having been originally breathed into a few forms or into one; and that, whilst this planet has gone cycling on according to the fixed law of gravity, from so simple a beginning endless forms most beautiful and most wonderful have been, and are being, evolved. — Charles Darwin (Darwin 1859) 5 Customisations and extensions

Contents 5.1 Front matter ...... 45 5.1.1 Shorten captions shown in the list of figures (PDF) . . 45 5.1.2 Shorten captions shown in the list of tables (PDF) . . . 45 5.2 Shorten running header (PDF) ...... 46 5.3 Unnumbered chapters ...... 46 5.4 Beginning chapters with quotes (PDF) ...... 46 5.5 Highlighting corrections (HTML & PDF) ...... 47 5.5.1 Short, inline corrections ...... 47 5.5.2 Blocks of added or changed material ...... 48 5.5.3 Stopping corrections from being highlighted ...... 48 5.6 Apply custom font color and highlighting to text (HTML & PDF) ...... 48 5.7 Including another paper in your thesis - embed a PDF document ...... 49 5.8 Including another paper in your thesis - R Markdown child document ...... 53 5.8.1 An example paper in another folder ...... 53 5.8.2 Step 1: Include paper as a child document ...... 54 5.8.3 Step 2: Make file paths compatible ...... 54 5.8.4 Step 3: Make sure header levels are correct ...... 55 5.8.5 Step 4. Make sure figure widths are correct . . . . 56 5.9 Customizing referencing ...... 57 5.9.1 Using a .csl file with pandoc instead of biblatex . 57 5.9.2 Customizing biblatex and adding chapter bibliographies 57 5.10 Customizing the page headers and footers (PDF) . . . 59 5.11 Diving in to the OxThesis LaTeX template (PDF) . . 60 5.12 Customising to a different university ...... 60 5.12.1 The minimal route ...... 60

44 5. Customisations and extensions

5.12.2 Replacing the entire title page with your required content 60

This chapter describes a number of additional tips and tricks as well as possible customizations to the oxforddown thesis.

5.1 Front matter

5.1.1 Shorten captions shown in the list of figures (PDF)

You might want your list of figures (which follows the table of contents) tohave shorter (or just different) figure descriptions than the actual figure captions.

Do this using the chunk option fig.scap (‘short caption’), for example {r captain-image, fig.cap="A very long and descriptive (and potentially boring) caption that doesn't fit in the list of figures, but helps the reader understand what the figure communicates.", fig.scap="A concise description for the list of figures"

5.1.2 Shorten captions shown in the list of tables (PDF)

You might want your list of tables (which follows the list of figures in your thesis front matter) to have shorter (or just different) table descriptions than the actual table captions.

If you are using knitr::kable to generate a table, you can do this with the argument caption.short, e.g.: knitr::kable(mtcars, caption = "A very long and descriptive (and ,→ potentially boring) caption that doesn't fit in the list of ,→ figures, but helps the reader understand what the figure communicates.", caption.short = "A concise description for the list of ,→ tables")

45 5. Customisations and extensions

5.2 Shorten running header (PDF)

You might want a chapter’s running header (i.e. the header showing the title of the current chapter at the top of page) to be shorter (or just different) to the actual chapter title.

Do this by adding the latex command \chaptermark{My shorter version} after your chapter title.

For example, chapter3‘s running header is simply ’Cites and cross-refs’, because it begins like this:

# Citations, cross-references, and collaboration {#cites-and-refs} \chaptermark{Cites and cross-refs}

5.3 Unnumbered chapters

To make chapters unnumbered (normally only relevant to the Introduction and/or the Conclusion), follow the chapter header with {-}, e.g. # Introduction {-}.

When you do this, you must also follow the heading with these two latex com- mands:

\adjustmtc \markboth{The Name of Your Unnumbered Chapter}{}

Otherwise the chapter’s mini table of contents and the running header will show the previous chapter.

5.4 Beginning chapters with quotes (PDF)

The OxThesis LaTeX template lets you inject some wittiness into your thesis by including a block of type savequote at the beginning of chapters. To do this, use the syntax ```{block type='savequote'}.1

1For more on custom block types, see the relevant section in Authoring Books with R Markdown.

46 5. Customisations and extensions

Add the reference for the quote with the chunk option quote_author="my author name". You will also want to add the chunk option include=knitr::is_latex_output() so that quotes are only included in PDF output.

It’s not possible to use markdown syntax inside chunk options, so if you want to e.g. italicise a book name in the reference use a ‘text reference’: Create a named piece of text with ‘(ref:label-name) My text’, then point to this in the chunk option with quote_author='(ref:label-name)'.

5.5 Highlighting corrections (HTML & PDF)

For when it comes time to do corrections, you may want to highlight changes made when you submit a post-viva, corrected copy to your examiners so they can quickly verify you’ve completed the task. You can do so like this:

5.5.1 Short, inline corrections

Highlight short, inline corrections by doing [like this]{.correction} — the text between the square brackets will then be highlighted in blue in the output.

Note that pandoc might get confused by citations and cross-references inside inline corrections. In particular, it might get confused by "[what @Shea2014 said]{.correction}" which becomes (what Shea et al. 2014, said){.correction} In such cases, you can use LaTeX syntax directly. The correction highlighting uses the soul package, so you can do like this:

• If using biblatex for references, use "\hl{what \textcite{Shea2014} said} • If using natbib for references, use "\hl{what \cite{Shea2014} said}

Using raw LaTeX has the drawback of corrections then not showing up in HTML output at all, but you might only care about correction highlighting in the PDF for your examiners anyway!

47 5. Customisations and extensions

5.5.2 Blocks of added or changed material

Highlight entire blocks of added or changed material by putting them in a block of type correction, using the syntax ```{block type='correction'}.2 Like so:

For larger chunks, like this paragraph or indeed entire figures, you can use the correction block type. This environment highlights paragraph-sized and larger blocks with the same blue colour.

Note that correction blocks cannot be included in word output.

5.5.3 Stopping corrections from being highlighted

To turn off correction highlighting, go to the YAML header of index.Rmd, then:

• PDF output: set corrections: false

• HTML output: remove or comment out - templates/corrections.css

5.6 Apply custom font color and highlighting to text (HTML & PDF)

The lua filter that adds the functionality to highlight corrections adds twomore tricks: you can apply your own choice of colour to highlight text, or change the font color. The syntax is as follows:

Here’s [some text in pink highlighting]{highlight="pink"} Becomes: Here’s some text in pink highlighting.

[Here's some text with blue font]{color="blue"} Becomes: Here’s some text with blue font

Finally — never, ever actually do this – [here's some text with black highlighting and yellow font]{highlight="black" color="yellow"} Becomes: here’s some text with black highlighting and yellow font

2In the .tex file for PDF output, this will put the content between \begin{correction} and \end{correction}; in gitbook output it will be put between and .

48 5. Customisations and extensions

The file scripts_and_filters/colour_and_highlight.lua implements this, if you want to fiddle around with it. It works with both PDF and HTML output.

5.7 Including another paper in your thesis - em- bed a PDF document

You may want to embed existing PDF documents into the thesis, for example if your department allows a ‘portfolio’ style thesis and you need to include an existing typeset publication as a chapter.

In gitbook output, you can simply use knitr::include_graphics and it should include a scrollable (and downloadable) PDF. You will probably want to set the chunk options out.width='100%' and out.height='1000px': knitr::include_graphics("figures/sample-content/pdf_embed_example/Lyngs2020_FB.pdf")

In LaTeX output, however, this approach can cause odd behaviour. Therefore, when you build your thesis to PDF, split the PDF into an alphanumerically sorted sequence of single-page PDF files (you can do this automatically with the package pdftools). You can then use the appropriate LaTeX command to insert them, as shown below (for brevity, in the oxforddown PDF sample content we’re only including two pages). Note that the chunk option results='asis' must be set. You may also want to remove margins from the PDF files, which you can do with Adobe Acrobat (paid version) and likely other software.

# install.packages(pdftools) # split PDF into pages stored in figures/sample-content/pdf_embed_example/split/ #

,→ pdftools::pdf_split("figures/sample-content/pdf_embed_example/Lyngs2020_FB.pdf", # output = "figures/sample-content/pdf_embed_example/split/")

# grab the pages pages <- ,→ list.files("figures/sample-content/pdf_embed_example/split", full.names = TRUE)

49 5. Customisations and extensions

# set how wide you want the inserted PDFs to be: # 1.0 is 100 per cent of the oxforddown PDF page width; # you may want to make it a bit bigger pdf_width <- 1.2

# for each PDF page, insert it nicely and # end with a page break cat(stringr::str_c("\\newpage\\begin{center} \\makebox[\\linewidth][c]{\\includegraphics[width=", pdf_width, "\\linewidth]{", pages, "}}\\end{center}"))

50 5. Customisations and extensions

CHI 2020 Paper CHI 2020, April 25–30, 2020, Honolulu, HI, USA

‘I Just Want to Hack Myself to Not Get Distracted’: Evaluating Design Interventions for Self-Control on Facebook

Ulrik Lyngs1, Kai Lukoff2, Petr Slovak3, William Seymour1, Helena Webb1, Marina Jirotka1, Jun Zhao1, Max Van Kleek1, Nigel Shadbolt1 1Department of Computer Science, University of Oxford, UK, {first.last}@cs.ox.ac.uk 2Human Centered Design & Engineering, University of Washington, Seattle, US, [email protected] 3Department of Informatics, King’s College London, UK, [email protected]

ABSTRACT Much of this work has focused on self-control over Facebook Beyond being the world’s largest social network, Facebook is use in student populations [2, 44, 46], with media multitasking for many also one of its greatest sources of digital distraction. research finding that students often give in to use which pro- For students, problematic use has been associated with nega- vides short-term ‘guilty pleasures’ over important, but aversive tive effects on academic achievement and general wellbeing. academic tasks [76, 88, 60]. In the present paper, we present a To understand what strategies could help users regain control, mixed-methods study exploring how two interventions to Face- we investigated how simple interventions to the Facebook UI book — goal reminders and removing the newsfeed — affect affect behaviour and perceived control. We assigned 58 uni- university students’ patterns of use and perceived control over versity students to one of three interventions: goal reminders, Facebook use. To triangulate self-report with objective mea- removed newsfeed, or white background (control). We logged surement, our study combined usage logging with fortnightly use for 6 weeks, applied interventions in the middle weeks, surveys and post-study interviews. and administered fortnightly surveys. Both goal reminders We found that both interventions helped participants stay on and removed newsfeed helped participants stay on task and task and use Facebook more in line with their intentions. In avoid distraction. However, goal reminders were often an- terms of use patterns, goal reminders led to less scrolling, noying, and removing the newsfeed made some fear missing fewer and shorter visits, and less time on site, whereas remov- out on information. Our findings point to future interventions ing the newsfeed led to less scrolling, shorter visits, and less such as controls for adjusting types and amount of available content ’liked’. However, goal reminders were often experi- information, and flexible blocking which matches individual enced as annoying, and removing the newsfeed made some definitions of ‘distraction’. participants fear missing out on information. After the study, participants suggested a range of design solutions to mitigate Author Keywords self-control struggles on Facebook, including controls for fil- Facebook; problematic use; self-control; distraction; ICT tering or removing the newsfeed, reminders of time spent and non-use; addiction; focus; interruptions of use goals, and removing features that drive engagement. As an exploratory study, this work should be followed by confir- CCS Concepts matory studies to assess whether our findings replicate, and • Human-centered computing Empirical studies in how they may generalise beyond a student population. HCI; →

INTRODUCTION RELATED WORK Research on ‘Problematic Facebook Use’ (PFU) has investi- Struggles with Facebook use gated correlations between Facebook use and negative effects Whereas many uses of Facebook offer important benefits, such on outcomes such as level of academic achievement [35] and as social support, rapid spread of information, or facilitation subjective wellbeing [58, 57]. A cross-cutting finding is that of real-world interactions [78], a substantial amount of re- negative outcomes are associated with difficulty at exerting search has focused on negative aspects [58]. For example, self-control over use, as well as specific use patterns including studies have reported correlations between patterns of Face- viewing friends’ wide-audience broadcasts rather than receiv- book use and lower academic achievement [77, 86], low self- ing targeted communication from strong ties [13, 58]. esteem, depression and anxiety [51], feelings of isolation and loneliness [2], and general psychological distress [15]. Such ‘Problematic Facebook Use’ (PFU) has been studied under Permission to make digital or hard copies of part or all of this work for personal or various names (including ‘Facebook dependence’ [87] and classroom use is granted without fee provided that copies are not made or distributed ‘Facebook addiction’[5]), but a recent review summarised a for profit or commercial advantage and that copies bear this notice and the full citation common definition as ‘problematic behaviour characterised on the first page. Copyrights for third-party components of this work must be honored. For all other uses, contact the owner/author(s). by addictive-like symptoms and/or self-regulation difficulties CHI ’20, April 25–30, 2020, Honolulu, HI, USA. related to Facebook use leading to negative consequences in © 2020 Copyright is held by the author/owner(s). ACM ISBN 978-1-4503-6708-0/20/04. personal and social life’ [58]. http://dx.doi.org/10.1145/3313831.3376672

Paper 543 Page 1

51 5. Customisations and extensions

REFERENCES [12] Gharad Bryan, Dean Karlan, and Scott Nelson. 2010. [1] Alexander T. Adams, Jean Costa, Malte F. Jung, and Commitment Devices. Annual Review of Economics 2, 1 Tanzeem Choudhury. 2015. Mindless Computing: (Sept. 2010), 671–698. DOI:http: Designing Technologies to Subtly Influence Behavior. In //dx.doi.org/10.1146/annurev.economics.102308.124324 Proceedings of the 2015 ACM International Joint [13] Moira Burke and Robert E. Kraut. 2016. The Conference on Pervasive and Ubiquitous Computing. Relationship Between Facebook Use and Well-Being ACM, 719–730. DOI: Depends on Communication Type and Tie Strength. http://dx.doi.org/10.1145/2750858.2805843 Journal of Computer-Mediated Communication 21, 4 [2] Sami Abdo Radman Al-Dubai, Kurubaran Ganasegeran, (2016), 265–281. DOI: Mustafa Ahmed Mahdi Al-Shagga, Hematram Yadav, http://dx.doi.org/10.1111/jcc4.12162 and John T. Arokiasamy. 2013. Adverse Health Effects and Unhealthy Behaviors among Medical Students [14] Moira Burke, Cameron Marlow, and Thomas Lento. Using Facebook. 2010. Social Network Activity and Social Well-Being. https://www.hindawi.com/journals/tswj/2013/465161/. In Proceedings of the SIGCHI Conference on Human (2013). DOI:http://dx.doi.org/10.1155/2013/465161 Factors in Computing Systems (CHI ’10). ACM, New York, NY, USA, 1909–1912. DOI: [3] All Party Parliamentary Group on Social Media and http://dx.doi.org/10.1145/1753326.1753613 Young People’s Mental Health and Wellbeing. 2019. #NewFilters to Manage the Impact of Social Media on [15] Wenhong Chen and Kye-Hyoung Lee. 2013. Sharing, Young People’s Mental Health and Wellbeing. Technical Liking, Commenting, and Distressed? The Pathway Report. UK Parliament. between Facebook Interaction and Psychological Distress. Cyberpsychology, Behavior and Social [4] Hunt Allcott, Luca Braghieri, Sarah Eichmeyer, and Networking 16, 10 (oct 2013), 728–734. DOI: Matthew Gentzkow. 2019. The Welfare Effects of Social http://dx.doi.org/10.1089/cyber.2012.0272 Media. Working Paper 25514. National Bureau of Economic Research. DOI: [16] Justin Cheng, Moira Burke, and Elena Goetz Davis. http://dx.doi.org/10.3386/w25514 2019. Understanding Perceptions of Problematic [5] Cecilie Schou Andreassen, Torbjørn Torsheim, Facebook Use: When People Experience Negative Life Geir Scott Brunborg, and Staale Pallesen. 2012. Impact and a Lack of Control. In Proceedings of the Development of a Facebook Addiction Scale. 2019 CHI Conference on Human Factors in Computing Psychological Reports 110, 2 (apr 2012), 501–517. DOI: Systems (CHI ’19). ACM, New York, NY, USA, DOI: http://dx.doi.org/10.2466/02.09.18.PR0.110.2.501-517 199:1–199:13. http://dx.doi.org/10.1145/3290605.3300429 [6] Yummy Apps. 2019. Todobook. (May 2019). [17] Jacob Cohen. 1992. A Power Primer. Psychological [7] Albert Bandura. 1982. Self-efficacy mechanism in Bulletin 112, 1 (1992), 155–159. DOI: human agency. American Psychologist 37, 2 (1982), http://dx.doi.org/10.1037/0033-2909.112.1.155 122–147. DOI: http://dx.doi.org/10.1037/0003-066x.37.2.122 [18] Anna L Cox, Sandy J J Gould, Marta E Cecchinato, [8] Fanni Bányai, Ágnes Zsila, Orsolya Király, Aniko Ioanna Iacovides, and Ian Renfree. 2016. Design Maraz, Zsuzsanna Elekes, Mark D. Griffiths, Frictions for Mindful Interactions: The Case for Proceedings of the 2016 CHI Cecilie Schou Andreassen, and Zsolt Demetrovics. Microboundaries. In Conference Extended Abstracts on Human Factors in 09-Jan-2017. Problematic Social Media Use: Results Computing Systems (CHI EA ’16). ACM, New York, NY, from a Large-Scale Nationally Representative DOI: Adolescent Sample. PLOS ONE 12, 1 (09-Jan-2017), USA, 1389–1397. http://dx doi org/10 1145/2851581 2892410 e0169839. DOI: . . . . http://dx.doi.org/10.1371/journal.pone.0169839 [19] Helen Creswick, Liz Dowthwaite, Ansgar Koene, [9] Elliot T Berkman, Cendri A Hutcherson, Jordan L Elvira Perez Vallejos, Virginia Portillo, Monica Cano, Livingston, Lauren E Kahn, and Michael Inzlicht. 2017. and Christopher Woodard. 2019. “. . . They don’t really Self-Control as Value-Based Choice. Current Directions listen to people”. Journal of Information, in Psychological Science 26, 5 (2017), 422–428. DOI: Communication and Ethics in Society 17, 2 (May 2019), http://dx.doi.org/10.1177/0963721417704394 167–182. DOI: http://dx.doi.org/10.1108/jices-11-2018-0090 [10] Walter R. Boot, Daniel J. Simons, Cary Stothart, and Cassie Stutts. 2013. The Pervasive Problem with [20] Angela L. Duckworth, Katherine L. Milkman, and Placebos in Psychology. Perspectives on Psychological David Laibson. 2018. Beyond Willpower: Strategies for Science 8, 4 (jul 2013), 445–454. DOI: Reducing Failures of Self-Control. Psychological http://dx.doi.org/10.1177/1745691613491271 Science in the Public Interest 19, 3 (Dec. 2018), 102–129. DOI: [11] Amara Brook. 2011. Ecological Footprint Feedback: http://dx.doi.org/10.1177/1529100618821893 Motivating or Discouraging? Social Influence 6, 2 (April 2011), 113–128. DOI: http://dx.doi.org/10.1080/15534510.2011.566801

Paper 543 Page 11

52 5. Customisations and extensions

5.8 Including another paper in your thesis - R Markdown child document

Sometimes you want to include another paper you are currently writing as a chapter in your thesis. Above 5.7, we described the simplest way to do this: include the other paper as a pdf. However, in some cases you instead want to include the R Markdown source from this paper, and have it compiled within your thesis. This is a little bit more tricky, because you need to keep careful track of your file paths, but it is possible by including the paper as a child document. There are four main steps:

1. Include the paper as a child document 2. Make file paths compatible with knitting the article on its own, aswell when it’s include in your thesis 3. Make header levels correct 4. Make figure widths correct

5.8.1 An example paper in another folder

Take this simple example (files for this are in this GitHub repository):

|--paper_to_include | |--my_paper.Rmd | |--data | | |--cat_salt.csv | |--figures | | |--cat.jpg | |--thesis

As the chart suggests, you have another folder, paper_to_include/ living in the same containing folder as your thesis folder. In the paper_to_include folder, the file my_paper.Rmd is where you write the paper. In my_paper.Rmd, you read in a CSV file found in the subfolder data/cats.csv, and also an image from the subfolder figures/cat.jpg.

53 5. Customisations and extensions

5.8.2 Step 1: Include paper as a child document

In your thesis folder, create an Rmd file for the chapter where you want to include another paper. Add one or more code chunks that include R Markdown files from that paper as child documents:

# Including an external chapter

```{r child = "../paper_to_include/my_paper.Rmd"} ```

5.8.3 Step 2: Make file paths compatible

Use parameters to adjust the file path of images based on values you set inthe YAML header of an R Markdown file. In my_paper.Rmd, create a parameter called other_path and set it to an empty string:

--- title: "A fabulous article in a different folder" params: other_path: "" ---

In my_paper.Rmd, put this at the start of the filepath when you read in data or include images: library(tidyverse) library(knitr) cat_data <- read_csv(str_c(params$other_path, "data/cats.csv")) include_graphics(str_c(params$other_path, "figures/cat.jpg"))

Finally, in your thesis folder’s index.Rmd file, also create the parameter other_path. But here, set it to where the paper_to_include/ folder is relative to your thesis folder: params: other_path: "../paper_to_include/"

54 5. Customisations and extensions

Note on HTML output

Note that if you want to host an HTML version on your thesis online, you will need to include graphics in the content that you host online - the internet obviously won’t be able to see filepaths that are just referring to stuff in another folder on your computer!

5.8.4 Step 3: Make sure header levels are correct

Unless the paper you want to include is also written as a book, your header levels are probably going to be off. That is, the level 1 headers (# Some header) you usefor main sections in the other paper turns into chaper titles when included in your thesis.

To avoid this, first increment all heading levels by one in paper_to_include/my_paper.Rmd (# Some header -> ## Some header). Then in paper_to_include/ create a lua filter that decrements header levels by one: Create a text file, save it as reduce_header_level.lua, and give it the content below. function Header(el) if( el.level <= 1) then error("I don't know how to decrease the level of h1") end el.level = el.level - 1 return el end

In the YAML header of paper_to_include/my_paper.Rmd, use this filter:

--- title: "A fabulous article in a different folder" params: other_path: "" output: pdf_document: pandoc_args:[ "--lua-filter=reduce_header_level.lua"] ---

Now, your header levels will be correct both when you knit the paper on its own and when its included in your thesis.

55 5. Customisations and extensions

NOTE: There might be no need to use a lua filter to shift heading - it seems you could simply use pandoc_args: ["--shift-heading-level-by=-1"] (see https: //pandoc.org/MANUAL.html#reader-options)

5.8.5 Step 4. Make sure figure widths are correct

It might be that your figure widths when knitting your paper on its own, andwhen including it in your thesis, need to be different. You can again use parameters to set figure widths.

Imagine you want figure width to be 80% of the page width when knitting yourpa- per on its own, but 100% in your thesis. In paper_to_include/my_paper.Rmd, first add a parameter we could call out_width and set it to the string “80%”:

--- title: "A fabulous article in a different folder" params: other_path: "" out_width: "80%" output: pdf_document: pandoc_args:[ "--lua-filter=reduce_header_level.lua"] ---

Then, make sure use that parameter to set the output width when you include figures in paper_to_include/my_paper.Rmd:

```{r, out.width=params$out_width, fig.cap="A very funny cat"} include_graphics(str_c(params$other_path, "figures/cat.jpg")) ```

Finally, create the parameter out_width in your thesis’ index.Rmd file: params: other_path: "../paper_to_include/" out_width: "80%"

Now, the output width of your figure will be 80% when knitting your paper on its own, and 100% when knitting it as child document of your thesis.

56 5. Customisations and extensions

5.9 Customizing referencing

5.9.1 Using a .csl file with pandoc instead of biblatex

The oxforddown package uses biblatex in LaTeX for referencing. It is also possible to use pandoc for referencing by providing a .csl file in the YAML header of index.Rmd (likely requiring commenting out the biblatex code in templates/template.tex). This may be helpful for those who have a .csl file describing the referencing format for a particular journal. However, note that this approach does not support chapter bibliographies (see Section 5.9.2). csl: ecology.csl

5.9.2 Customizing biblatex and adding chapter bibliogra- phies

This section provides one example of customizing biblatex. Much of this code was combined from searches on Stack Exchange and other sources (e.g. here).

In templates/template.tex, one can replace the existing biblatex calls with the following to achieve referencing that looks like this:

(Charmantier and Gienapp 2014)

Charmantier, A. and P. Gienapp (2014). Climate change and timing of avian breeding and migration: evolutionary versus plastic changes. Evolutionary Ap- plications 7(1):15–28. doi: 10.1111/eva.12126.

\usepackage[backend=biber, bibencoding=utf8, refsection=chapter, % referencing by chapter style=authoryear, firstinits=true, isbn=false, doi=true, url=false, eprint=false, related=false, dashed=false,

57 5. Customisations and extensions

clearlang=true, maxcitenames=2, mincitenames=1, maxbibnames=10, abbreviate=false, minbibnames=3, uniquelist=minyear, sortcites=true, date=year ]{biblatex} \AtEveryBibitem{% \clearlist{language}% \clearfield{note} }

\DeclareFieldFormat{titlecase}{\MakeTitleCase{#1}}

\newrobustcmd{\MakeTitleCase}[1]{%

,→ \ifthenelse{\ifcurrentfield{booktitle}\OR\ifcurrentfield{booksubtitle}% \OR\ifcurrentfield{maintitle}\OR\ifcurrentfield{mainsubtitle}%

,→ \OR\ifcurrentfield{journaltitle}\OR\ifcurrentfield{journalsubtitle}%

,→ \OR\ifcurrentfield{issuetitle}\OR\ifcurrentfield{issuesubtitle}%

,→ \OR\ifentrytype{book}\OR\ifentrytype{mvbook}\OR\ifentrytype{bookinbook}% \OR\ifentrytype{booklet}\OR\ifentrytype{suppbook}% \OR\ifentrytype{collection}\OR\ifentrytype{mvcollection}% \OR\ifentrytype{suppcollection}\OR\ifentrytype{manual}% \OR\ifentrytype{periodical}\OR\ifentrytype{suppperiodical}% \OR\ifentrytype{proceedings}\OR\ifentrytype{mvproceedings}% \OR\ifentrytype{reference}\OR\ifentrytype{mvreference}% \OR\ifentrytype{report}\OR\ifentrytype{thesis}} {#1} {\MakeSentenceCase{#1}}}

% \renewbibmacro{in:}{} % suppress "in" for articles % \renewbibmacro{in:}{% \ifentrytype{article}{}{\printtext{\bibstring{in}\intitlepunct}}} %-- no "quotes" around titles of chapters/article titles \DeclareFieldFormat[article, inbook, incollection, inproceedings, ,→ misc, thesis, unpublished]

58 5. Customisations and extensions

{title}{#1} %-- no punctuation after volume \DeclareFieldFormat[article] {volume}{{#1}} %-- puts number/issue between brackets \DeclareFieldFormat[article, inbook, incollection, inproceedings, ,→ misc, thesis, unpublished] {number}{\mkbibparens{#1}} %-- and then for articles directly the pages w/o any "pages" or ,→ "pp." \DeclareFieldFormat[article] {pages}{#1} %-- for some types replace "pages" by "p." \DeclareFieldFormat[inproceedings, incollection, inbook] {pages}{p. #1} %-- format 16(4):224--225 for articles \renewbibmacro*{volume+number+eid}{ \printfield{volume}% \printfield{number}% \printunit{\addcolon} }

If you would like chapter bibliographies, in addition insert the following code at the end of each chapter, and comment out the entire REFERENCES section at the end of template.tex.

\printbibliography[segment=\therefsection,heading=subbibliography]

5.10 Customizing the page headers and footers (PDF)

This can now be done directly in index.Rmd’s YAML header. If you are a LaTeX expert and need further customisation that what’s currently provided, you can tweak the relevant sections of templates/template.tex - the relevant code is beneath the line that begins \usepackage{fancyhdr}.

59 5. Customisations and extensions

5.11 Diving in to the OxThesis LaTeX template (PDF)

For LaTeX minded people, you can read through templates/template.tex to see which additional customisation options are available as well as templates/ociamthesis.cls which supplies the base class. For example, template.tex provides an option for master’s degree submissions, which changes identifying information to candidate number and includes a word count. At the time of writing, you must set this directly in template.tex rather than from the YAML header in index.Rmd.

5.12 Customising to a different university

5.12.1 The minimal route

If the front matter in the OxThesis LaTeX template is suitable to your university, customising oxforddown to your needs could be as simple as putting the name of your institution and the path to your university’s logo in index.Rmd: university: University of You university-logo: figures/your-logo-here.pdf

5.12.2 Replacing the entire title page with your required content

If you have a .tex file with some required front matter from your university that you want to replace the OxThesis template’s title page altogether, you can provide a filepath to this file in index.Rmd. oxforddown’s sample content includes and example of this — if you use the YAML below, your front matter will look like this: alternative-title-page: ,→ front-and-back-matter/alt-title-page-example.tex

60 5. Customisations and extensions

Title of your Title of your Thesis thesis

Thesis committee

Promotor: Prof.dr J. Smith Professor of Geo-information Science and Remote Sensing Wageningen University

Co-promotors: Dr. Name of co-promotor Assistant Professor, Laboratory of Geo-information Science and Remote Sensing Thesis Wageningen University submitted in fulfilment of the requirements for the degree of doctor at Wageningen University Other members: by the authority of the Rector Magnificus Prof.dr Jury member 1, Wageningen University Prof. Dr A.P.J. Mol, Prof.dr Jury member 2, Aliation in the presence of the Prof.dr Jury member 3, Aliation Thesis Committee appointed by the Academic Board Prof.dr Jury member 4, Aliation to be defended in public on Date of your defense John Doe This research was conducted under the auspices of the C.T. de Wit Graduate School at 4 p.m. in the Aula. of Production Ecology & Resource Conservation (PE&RC)

Acknowledgements

This is where you will normally thank your advisor, colleagues, family and friends, as well as funding and institutional support. In our case, we will give our praises to the people who developed the ideas and tools that allow us to push open science a little step forward by writing plain-text, transparent, and reproducible theses in R Markdown. We must be grateful to John Gruber for inventing the original version of Markdown, to John MacFarlane for creating Pandoc (http://pandoc.org) which For Yihui Xie converts Markdown to a large number of output formats, and to Yihui Xie for creating knitr which introduced R Markdown as a way of embedding code in Markdown documents, and bookdown which added tools for technical and longer-form writing. Special thanks to Chester Ismay, who created the thesisdown package that helped many a PhD student write their theses in R Markdown. And a very special thanks to John McManigle, whose adaption of Sam Evans’ adaptation of Keith Gillow’s original maths template for writing an Oxford University DPhil thesis in LaTeX provided the template that I in turn adapted for R Markdown. Finally, profuse thanks to JJ Allaire, the founder and CEO of RStudio, and Hadley Wickham, the mastermind of the tidyverse without whom we’d all just given up and done data science in Python instead. Thanks for making data science easier, more accessible, and more fun for us all.

Ulrik Lyngs Linacre College, Oxford 2December2018 John Doe Title of your thesis ?? pages.

PhD thesis, Wageningen University, Wageningen, NL (2015) With references, with summary in English

ISBN XXX-YYY

61 6 Troubleshooting

This chapter describes common errors you may run into, and how to fix them.

6.1 Error: Failed to build the bibliography via biber

This can happen if you’ve had a failed build, perhaps in relation to RStudio shutting down abruptly.

Try doing this:

1. type make clean-knits in the terminal tab (or run file.remove(list.files(pattern = "*.(log|mtc|maf|aux|bbl|blg|xml)")) in the R console) to clean up files generated by LaTeX during a build 2. restart your computer

If this does not solve the problem, try using the natbib LaTeX package instead of biblatex for handling references. To do this, go to index.Rmd and

1. set use-biblatex: false and use-natbib: true 2. set citation_package: natbib under

62 6. Troubleshooting output: bookdown::pdf_book: citation_package: natbib

63 Alles Gescheite ist schon gedacht worden. Man muss nur versuchen, es noch einmal zu denken. All intelligent thoughts have already been thought; what is necessary is only to try to think them again. — Johann Wolfgang von Goethe (von Goethe 1829) Conclusion

If we don’t want Conclusion to have a chapter number next to it, we can add the {-} attribute.

And here’s some other random info: the first paragraph after a chapter title or section head shouldn’t be indented, because indents are to tell the reader that you’re starting a new paragraph. Since that’s obvious after a chapter or section title, proper typesetting doesn’t add an indent there. This paragraph, by contrast, will be indented as it should because it is not the first one after the ‘More info’ heading. All hail LaTeX. (If you’re readingthe HTML version, you won’t see any indentation - have a look at the PDF version to understand what in the earth this section is babbling on about).

64 Appendices

65 A The First Appendix

This first appendix includes an R chunk that was hidden in the document (using echo = FALSE) to help with readibility: In 02-rmd-basics-code.Rmd library(tidyverse) knitr::include_graphics("figures/sample-content/chunk-parts.png")

And here’s another one from the same chapter, i.e. Chapter 2.2: knitr::include_graphics("figures/sample-content/beltcrest.png")

66 B The Second Appendix, for Fun

67 Works Cited

Darwin, Charles (1859). On the Origin of Species by Means of Natural Selection or the Preservation of Favoured Races in the Struggle for Life. London: John Murray. Von Goethe, Johann Wolfgang (1829). Wilhelm Meisters Wanderjahre oder die Entsagenden. de. Cotta. Lottridge, Danielle et al. (2012). “Browser design impacts multitasking”. In: Proceedings of the Human Factors and Ergonomics Society 56th Annual Meeting. doi: 10.1177/1071181312561289. Lyngs, Ulrik (2019). oxforddown: An Oxford University Thesis Template for R Markdown. https://github.com/ulyngs/oxforddown. doi: 10.5281/zenodo.3484682. Shea, Nicholas et al. (2014). “Supra-personal cognitive control and metacognition”. In: Trends in Cognitive Sciences 18.4, pp. 186–193. doi: 10.1016/j.tics.2014.01.006. url: http://dx.doi.org/10.1016/j.tics.2014.01.006. Wu, Tim (2016). The Attention Merchants: The Epic Scramble to Get Inside Our Heads. Knopf Publishing Group.

Macquarie University Logo

  • Help & FAQ

thesisdownmq: An updated R Markdown thesis template using the bookdown package for Macquarie University HDR Thesis

Research output : Non-traditional research output › Software

Original languageEnglish
Place of Publicationgithub.com
Media of outputOnline
Publication statusPublished - 2018

Access to Document

  • https://github.com/thomas-fung/thesisdownmq

T1 - thesisdownmq

T2 - An updated R Markdown thesis template using the bookdown package for Macquarie University HDR Thesis

AU - Fung, Ho-Ting

AU - Wishart, Justin

M3 - Software

CY - github.com

R-bloggers

R news and tutorials contributed by hundreds of R bloggers

R markdown senior thesis template.

Posted on November 17, 2015 by chesterismay in R bloggers | 0 Comments

[social4i size="small" align="align-left"] --> [This article was first published on Chester's R blog » R , and kindly contributed to R-bloggers ]. (You can report issue about the content on this page here ) Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

“Science is reportedly in the middle of a reproducibility crisis.” This is the claim of quite a few these days including an article from ROpenSci which directly references another article by The Conversation . But what is “reproducible research” and how can statistical tools be used to help facilitate it?

I agree with Roger Peng and the folks behind Coursera's massively popular Data Science Specialization and the front page of their Reproducible Research course on their definition of “reproducible research”:

Reproducible research is the idea that data analyses, and more generally, scientific claims, are published with their data and software code so that others may verify the findings and build upon them. The need for reproducibility is increasing dramatically as data analyses become more complex, involving larger datasets and more sophisticated computations. Reproducibility allows for people to focus on the actual content of a data analysis, rather than on superficial details reported in a written summary. In addition, reproducibility makes an analysis more useful to others because the data and code that actually conducted the analysis are available.

One of the current goals at Reed is for students to be engaged in the research process earlier on in their academic careers in order to make their senior thesis experience more meaningful and rewarding. The collecting and analysis of data has been a challenging part of this process in the past for students. Additionally, updating statistical analyses, plots, and bibliographies as advisors request has sometimes been time consuming and frustrating.

So how does this tie into the reproducible research concept? As more and more students use R Markdown while taking courses at Reed (Chem 101/102, Mathematics 141, Mathematics 243, and Bio 101/102 next year!), it became clear that an option to use R Markdown while generating the senior thesis document should be available. The simplicity of Markdown commands improves readability and documentation, which make it a great thesis writing environment. R Markdown provides a wonderful environment to publish data and software code along with text and commentary and, in my opinion, is the best software currently available for writing journal articles, homework assignments, AND senior theses….reproducible senior theses!

What I'll be discussing in this blog post is a template I've created using R Markdown for Reed College senior theses. This template derives a lot of the features of the current LaTeX template (in fact it directly calls this template) so you can expect many of the great things from that including automatic creation of figure and table numbers, a table of contents, easy addition of beautiful plots and graphics, and the use of bibiolography style files. (Do you really want to have to memorize what APA or MLA looks like?…No!) In addition, you won't need to learn LaTeX. I've done the hard work of getting all that set up. You only need to learn Markdown . (Don't worry. That's really not hard!)

Markdown allows you to write in an easy-to-read, easy-to-write plain text format, which then converts to a variety of different formats. R Markdown , which is really just Markdown with the ability to add in R code and output directly, allows you to produce HTML, PDF, and even Word documents based on only one Markdown file! The sky is the limit for Markdown !

The thesis template will automatically convert the Markdown code you type to LaTeX code which will then produce a PDF document. Again, I've done the hard work of getting this Markdown code to produce the correct output. If you'd like to check out the current version of this PDF, it is available on Google Drive here .

Now, back to Markdown basics. You can find a lot more information on Markdown here and an interactive tutorial here . You'll get used to it before you know it. Probably in less than an hour!

Install the template generating package

After you've stepped through the basics of Markdown , it's time to check out this template for yourself. Make sure you have RStudio and LaTeX installed and then direct your browser to the GitHub page for the template: http://github.com/ismayc/rticles . You'll see instructions there in the README.md file near the bottom of the page on installing the template package and getting the template running. As you see there, you'll want to install the rticles package via the following commands in the RStudio console:

This allows for Reed Senior Thesis to be an option when you create a new R Markdown file via the File -> New File -> R Markdown dialog. You can specify the name you would like to give the file and also the location where you'd like the template and its files to be stored. I've called it “MyReedThesis” in what follows. After hitting the OK button, you'll see an Rmd file load up onto your RStudio window. (It will be called the same thing as what you specified in the previous step.)

If you click on the folder you've just created in the Files tab in RStudio, you can see a lot of files that have been created to assist you. You will see Rmd files for the abstract, bibliography, different chapters, conclusion, and your main Rmd file ( MyReedThesis.Rmd for me). You also see folders that hold your bibliography database files ( bib ), bibliography style files ( csl ), data files ( data ), and images ( figure ). You'll find that I've preloaded a bibliography database file ( thesis.bib ), an American Psychological Association (APA) style file ( apa.csl ) from the Zotero Style Repository , a dataset derived from departing flights from Seattle and Portland in 2014 ( flights.csv ), and a couple figures in the figure folder.

If you click on the Knit button near the top of the RStudio window on your main Rmd file, a PDF linking together all of the files will be created. I've tried to show you how to do a variety of things in this Markdown template including

In the Introduction

  • Creating a different headers including a chapter using the # syntax, a section using ## , a subsection using ### , etc.
  • Bolding of text by surrounding the text in ** or __
  • Adding a comment using the <!-- and --> syntax

In Chapter 1

  • Easily creating numbered or non-numbered lists
  • Using whitespace to create a new paragraph in your output
  • Including R code in chunks to be added into your document
  • Specifying different chunk options to tweak the output
  • Using inline R code for calculations and directly referring to R results in the text of your document
  • Including plots created in R
  • Creating tables based on data stored in R
  • Creating hyperlinks to web resources

In Chapter 2

  • Including mathematical equations
  • Using LaTeX to create chemical reaction equations
  • Adding other discipline specific content to your theses

In Chapter 3

  • Creating tables using Pandoc
  • Labelling and referencing tables and figures (both created in R and stored in files) using custom R functions I created
  • Adding footnotes into your document
  • Developing bibliography database files using Zotero (highly recommended) or other programs like BibDesk

In the Conclusion

  • Making a few tweaks to how chapters are displayed
  • Creating appendices if desired

Lastly, in the bibliography.Rmd file, you'll find ways to currently fix the hanging indent issue with some citation styles. (You might need to delete a few lines if your style doesn't require hanging indents.) I also provide a way to cite sources in your bibliography at the end of the document that you don't directly cite throughout your thesis here.

The main driver R Markdown file

If you go back to the main Rmd file that is open, you'll see a lot of text that is commented out. This provides more information about what is happening in this file. In summary, this file links all of the chapter files together and creates a way to input the preliminaries (the abstract, the preface, etc.) as either inline text at the top of the document or in a file stored like abstract.Rmd . You'll also change your name, your advisor's name, and other metadata here. One last thing: lot stands for “List of Tables” and lof stands for “List of Figures.” These are automatically created when you include a table or a figure into your theses.

Currently, everything links throughout the document as well. When you make a reference to Figure 3.1 in Chapter 2, you can click on that link in the PDF and it will go directly to that figure. Chapters and sections are also linked in this same fashion.

There will be slight modifications (hopefully only slight if any at all!) occurring to this document as students and faculty test it throughout this year. I highly recommend running devtools::install_github("ismayc/rticles") and creating a new template from time to time to make sure you have the latest version of the template. You can easily copy your files into the new template as needed. (Some of the changes may occur to LaTeX files that you won't directly access.)

I'm hopeful that this template will be of great use to seniors throughout Reed College this year and in years to come. Science majors may get the most immediate benefit, but I believe that Markdown is an incredible valuable language to learn. It's easy and extremely flexible in the type of output it can produce. I've written this template to be as user friendly as possible and I hope that non-science majors will consider using it! If you have any questions, feedback, or would like to report any issues, please email me .

(The generating R Markdown file for this HTML document—saved in the .Rmd extension—is available here .)

thesis template r markdown

To leave a comment for the author, please follow the link and comment on their blog: Chester's R blog » R . R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job . Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Copyright © 2022 | MH Corporate basic by MH Themes

Never miss an update! Subscribe to R-bloggers to receive e-mails with the latest R posts. (You will not see this message again.)

thesis template r markdown

  • About ITS Staff / Contact Us
  • Teaching With Technology
  • Center for Teaching and Learning Website

Updated R Markdown thesis template

In October of 2015, I released an R Markdown senior thesis template R package and discussed it in the blogpost here . It was well-received by students and faculty that worked with it and this past summer I worked on updating it to make it even nicer for students. The big addition is the ability for students to export their senior thesis to a webpage (example here ) and also label and cross-reference figures and tables more easily. These additions and future revisions will be in the new thesisdown package in the spirit of the bookdown package developed and released by RStudio in summer 2016.

I encourage you to look over my blog post last year to get an idea of why R Markdown is such a friendly environment to work in. Markdown specifically allows for typesetting of the finished document to be transparent inside the actual document. Down the road, it is my hope that students will be able to write generating R Markdown files that will then export into many formats. These currently include the LaTeX format to produce a PDF following Reed’s senior thesis guidelines and the HTML version in gitbook style. Eventually, this will include a Word document following Reed’s guidelines and also an ePub (electronic book) version. These last two are available at the moment but are not fully functional.

By allowing senior theses in a variety of formats, seniors will be more easily able to display their work to potential employers, other students, faculty members, and potential graduate schools. This will allow them to get the word out about their studies and research while still encouraging reproducibility in their computations and in their analyses.

Install the template generating package

To check out the package yourself, make sure you have RStudio and LaTeX installed (directions under R Tutorials here) and then direct your browser to the GitHub page for the template: http://github.com/ismayc/thesisdown . The README.md file near the bottom of the page below the files gives directions on installing the template package and getting the template running. As you see there, you’ll want to install the thesisdown package via the following commands in the RStudio console:

If you have any questions, feedback, or would like to report any issues, please email me .

(The generating R Markdown file for this HTML document—saved in the .Rmd extension—is available here .)

  • Search for:
  • Mobile App Recommendations
  • Foreign Language Faculty Newsletter Archive

Multimedia Projects

  • Preproduction
  • Post-Production (aka Editing)
  • Using iMovie
  • Recording and Editing Audio with GarageBand
  • Detaching audio from a video file using the Quicktime player

Screen Capturing your Mac Computer

  • Screen Capturing your Mac Computer Screen
  • Recording a Video of Your Mac Screen Using QuickTime
  • Mirror your ipad or iphone’s screen to your Mac computer

Creating H5P Content

  • Creating H5P Content in Moodle
  • Creating H5P content in WordPress
  • H5P examples

Recent Entries

  • Dual Filament Printing
  • H5p Example: Image Hotspots
  • Customizing a 3d Model
  • Mother 32 and DFAM (drummer from another mother) at PARC
  • Retreat! Strategy, sandwiches, stroopwaffles

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.

oxforddown : An Oxford University Thesis Template for R Markdown

2 r markdown basics.

Here is a brief introduction to using R Markdown . Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents and much, much more. R Markdown provides the flexibility of Markdown with the implementation of R input and output. For more details on using R Markdown see http://rmarkdown.rstudio.com .

2.1 Basic markdown syntax

2.1.1 whitespace.

Be careful with your spacing. While whitespace largely is ignored, it does at times give markdown signals as to how to proceed. As a habit, try to keep everything left aligned whenever possible, especially as you type a new paragraph. In other words, there is no need to indent basic text in the Rmd document (in fact, it might cause your text to do funny things if you do).

2.1.2 Italics and bold

  • Italics are done like *this* or _this_
  • Bold is done like **this** or __this__
  • Bold and italics is done like ***this***, ___this___, or (the most transparent solution, in my opinion) **_this_**

2.1.3 Inline code

  • Inline code is created with backticks like `this`

2.1.4 Sub and superscript

Sub 2 and super 2 script is created like this~2~ and this^2^

2.1.5 Strikethrough

  • Strikethrough is done ~~like this~~

2.1.6 ‘Escaping’ (aka “What if I need an actual asterisk?”)

  • To include an actual *, _ or \, add another \ in front of them: \*, \_, \\

2.1.7 Endash (–), emdash (—)

  • – and — with -- and ---

2.1.8 Blockquotes

Do like this:

Put a > in front of the line.

2.1.9 Headings

Section headers are created with #’s of increasing number, i.e. 

  • # First-level heading
  • ## Second-level heading

In PDF output, a level-five heading will turn into a paragraph heading, i.e.  \paragraph{My level-five heading} , which appears as bold text on the same line as the subsequent paragraph.

2.1.10 Lists

Unordered list by starting a line with an * or a -:

Ordered lists by starting a line with a number. Notice that you can mislabel the numbers and Markdown will still make the order right in the output:

To create a sublist, indent the values a bit (at least four spaces or a tab):

2.1.11 Line breaks

The official Markdown way to create line breaks is by ending a line with more than two spaces.

Roses are red. Violets are blue.

This appears on the same line in the output, because we didn’t add spaces after red.

This appears with a line break because I added spaces after red.

I find this is confusing, so I recommend the alternative way: Ending a line with a backslash will also create a linebreak:

To create a new paragraph, you put a blank line.

Therefore, this line starts its own paragraph.

2.1.12 Hyperlinks

  • This is a hyperlink created by writing the text you want turned into a clickable link in [square brackets followed by a](https://hyperlink-in-parentheses)

2.1.13 Footnotes

  • Are created 1 by writing either ^[my footnote text] for supplying the footnote content inline, or something like [^a-random-footnote-label] and supplying the text elsewhere in the format shown below 2 :

[^a-random-footnote-label]: This is a random test.

2.1.14 Comments

To write comments within your text that won’t actually be included in the output, use the same syntax as for writing comments in HTML. That is, <!-- this will not be included in the output -->.

2.1.15 Math

The syntax for writing math is stolen from LaTeX. To write a math expression that will be shown inline , enclose it in dollar signs. - This: $A = \pi*r^{2}$ Becomes: \(A = \pi*r^{2}\)

To write a math expression that will be shown in a block, enclose it in two dollar signs. This: $ $A = \pi*r^{2}$$

Becomes: \[A = \pi*r^{2}\]

To create numbered equations, put them in an ‘equation’ environment and give them a label with the syntax (\#eq:label) , like this:

Becomes: \[\begin{equation} f\left(k\right)=\binom{n}{k}p^k\left(1-p\right)^{n-k} \tag{2.1} \end{equation}\]

For more (e.g. how to theorems), see e.g. the documentation on bookdown.org

2.2 Executable code chunks

The magic of R Markdown is that we can add executable code within our document to make it dynamic.

We do this either as code chunks (generally used for loading libraries and data, performing calculations, and adding images, plots, and tables), or inline code (generally used for dynamically reporting results within our text).

The syntax of a code chunk is shown in Figure 2.1 .

Code chunk syntax

Figure 2.1: Code chunk syntax

Common chunk options include (see e.g.  bookdown.org ):

  • echo : whether or not to display code in knitted output
  • eval : whether or to to run the code in the chunk when knitting
  • include : whether to include anything from the from a code chunk in the output document
  • fig.cap : figure caption
  • fig.scap : short figure caption, which will be used in the ‘List of Figures’ in the PDF front matter

IMPORTANT : Do not use underscoores in your chunk labels - if you do, you are likely to get an error in PDF output saying something like “! Package caption Error: \caption outside float”.

2.2.1 Setup chunks - setup, images, plots

An R Markdown document usually begins with a chunk that is used to load libraries , and to set default chunk options with knitr::opts_chunk$set .

In your thesis, this will probably happen in index.Rmd and/or as opening chunks in each of your chapters.

2.2.2 Including images

Code chunks are also used for including images, with include_graphics from the knitr package, as in Figure 2.2

Oxford logo

Figure 2.2: Oxford logo

Useful chunk options for figures include:

  • out.width (use with a percentage) for setting the image size
  • if you’ve got an image that gets waaay to big in your output, it will be constrained to the page width by setting out.width = "100%"

Figure rotation

You can use the chunk option out.extra to rotate images.

The syntax is different for LaTeX and HTML, so for ease we might start by assigning the right string to a variable that depends on the format you’re outputting to:

Then you can reference that variable as the value of out.extra to rotate images, as in Figure 2.3 .

Oxford logo, rotated

Figure 2.3: Oxford logo, rotated

2.2.3 Including plots

Similarly, code chunks are used for including dynamically generated plots. You use ordinary code in R or other languages - Figure 2.4 shows a plot of the cars dataset of stopping distances for cars at various speeds (this dataset is built in to R ).

A ggplot of car stuff

Figure 2.4: A ggplot of car stuff

Under the hood, plots are included in your document in the same way as images - when you build the book or knit a chapter, the plot is automatically generated from your code, saved as an image, then included into the output document.

2.2.4 Including tables

Tables are usually included with the kable function from the knitr package.

Table 2.1 shows the first rows of that cars data - read in your own data, then use this approach to automatically generate tables.

Table 2.1: A knitr kable table
speed dist
4 2
4 10
7 4
7 22
8 16
9 10
  • Gotcha: when using kable , captions are set inside the kable function
  • The kable package is often used with the kableExtra package

2.2.5 Control positioning

One thing that may be annoying is the way R Markdown handles “floats” like tables and figures. In your PDF output, LaTeX will try to find the best place to put your object based on the text around it and until you’re really, truly done writing you should just leave it where it lies.

In general, you should allow LaTeX to do this, but if you really really need a figure to be positioned where you put in the document, then you can make LaTeX attempt to do this with the chunk option fig.pos="H" , as in Figure 2.5 :

An Oxford logo that LaTeX will try to place at this position in the text

Figure 2.5: An Oxford logo that LaTeX will try to place at this position in the text

As anyone who has tried to manually play around with the placement of figures in a Word document knows, this can have lots of side effects with extra spacing on other pages, etc. Therefore, it is not generally a good idea to do this - only do it when you really need to ensure that an image follows directly under text where you refer to it (in this document, I needed to do this for Figure 4.1 in section 4.1.4 ). For more details, read the relevant section of the R Markdown Cookbook .

2.3 Executable inline code

‘Inline code’ simply means inclusion of code inside text. The syntax for doing this is `r R_CODE` For example, `r 4 + 4` will output 8 in your text.

You will usually use this in parts of your thesis where you report results - read in data or results in a code chunk, store things you want to report in a variable, then insert the value of that variable in your text. For example, we might assign the number of rows in the cars dataset to a variable:

We might then write: “In the cars dataset, we have `r num_car_observations` observations.”

Which would output: “In the cars dataset, we have 50 observations.”

2.4 Executable code in other languages than R

If you want to use other languages than R, such as Python, Julia C++, or SQL, see the relevant section of the R Markdown Cookbook

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 You must be signed in to change notification settings

An updated R Markdown thesis template using the bookdown package; edited to work with the University of Florida dissertation template.

ksauby/thesisdownufl

Folders and files.

NameName
59 Commits
rmarkdown/templates/thesis rmarkdown/templates/thesis

Repository files navigation

This project was inspired by the bookdown package and is an updated version of my Senior Thesis template in the reedtemplates package here .

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.

The current output for the four versions is here:

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

Under the hood, the Reed College LaTeX template (and soon the Reed College Word 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 thesisdown has some prerequisites which are described below. To compile PDF documents using R , you are going to need to have LaTeX installed. It can be downloaded for Windows at http://http://miktex.org/download and for Mac at http://tug.org/mactex/mactex-download.html . Follow the instructions to install the necessary packages after downloading the (somewhat large) installer files. You may need to install a few extra LaTeX packages on your first attempt to knit as well.

Using thesisdown from Chester's GitHub

To use thesisdown from RStudio:

Install the latest RStudio .

Install the bookdown and thesisdown packages:

  • Use the New R Markdown dialog to select Thesis :

New R Markdown

Note that this will currently only Knit if you name the directory index as shown above.

Get the Reddit app

Subreddit for the University of Nevada, Reno.

Rmarkdown thesis template for those less familiar with LaTeX

Here is the template: https://github.com/SchisslerGroup/UNR-thesis-template

This is probably going to be of interest to a few who see this, but I've put together a thesis template that meets all the style guidelines for a UNR thesis (see here for formatting requirements ). Generally students will write and format their thesis using Word or LaTeX. Word is simple, but makes it difficult to include more powerful features like cross-references. LaTeX is fully featured, but has a very steep learning curve. The template I'm offering here is a compromise that lets you write your thesis simply while offering the important features of LaTeX.

This template is designed to be used within RStudio, an editor for the R programming language, and compiles to an HTML version that can be read online and a PDF version that is ready for submission. It works by using an R package called bookdown which is generally used for creating HTML books. I've modified a LaTeX template so that it matches the formatting guidelines. All you need to do is write your chapters in an Rmarkdown file (.Rmd) and hit 'build book'. If your research happens to use a programming language then you're in luck! Many scripting languages (mainly R and Python) can be directly embedded into the Rmd file and run in chunks.

Don't worry if you don't know any R programming, it's not necessary to produce a document. What is expected is the ability to

Download and install R and RStudio

Clone/Download a github repository

Modify a few simple files for your own use

Use markdown syntax (common for various web forums including Reddit)

Ask questions when you are stuck

This template is provided as is, and I am happy to talk with anyone who is interested in using it. You can ask me questions here, in a direct message, or open an issue on the repo with the question tag.

The template repository has an example of the html output, and there is a button at the top of that html book page where you can download the pdf version ( link to page and link to pdf ).

Other features of using Rmarkdown to write your thesis:

Easy embedding of formulas/equations

Easy cross references, footnotes, bibliography, etc

Ability to reference tables, figures, and equations

Use R to perform analyses and produce plots

Full documentation and list of features can be found on the bookdown website https://bookdown.org/yihui/bookdown/

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. Welcome

    Abstract. 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 Markdown, and largely follows the structure ...

  3. Writing your thesis

    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 ...

  4. GitHub

    To use ufcdown from RStudio:. 1) Ensure that you have already installed LaTeX and the fonts described above, and are using the latest version of RStudio.You can use ufcdown 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.

  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. PDF oxforddown

    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 .

  8. GitHub

    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. ismayc/thesisdown: An updated R Markdown thesis template using the

    Using the bookdown package and LaTeX and Word thesis templates from Reed College, this package aims to encourage reproducible research using simple Markdown syntax while embedding all of the R code to produce plots and analyses as well.

  10. Updated R Markdown thesis template

    In October of 2015, I released an R Markdown senior thesis template R package and discussed it in the blogpost here. It was well-received by students and faculty that worked with it and this past summer I worked on updating it to make it even nicer for students.

  11. GitHub

    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.

  12. 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 ...

  13. Oxforddown: an Oxford University Thesis Template for R Markdown

    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 LATEX template (most recently adapted by John McManigle). This template's sample content include illustrations of how to write a thesis in R ...

  14. 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):

  15. thesisdownmq: An updated R Markdown thesis template using the bookdown

    thesisdownmq: An updated R Markdown thesis template using the bookdown package for Macquarie University HDR Thesis. Fung, Ho-Ting (Author); Wishart, Justin (Author). 2018. github.com. Research output: Non-traditional research output › Software

  16. PDF stevetemplates: Steve's R Markdown Templates

    Title Steve's R Markdown Templates Depends R (>= 3.5.0) Version 1.0.0 Author Steven V. Miller ... ekohist_thesis Stockholm University EKOHIST Thesis Template Description This is a specialty LaTeX R Markdown template for which I am not anticipating there will be high demand. This is for master's students in the Department of Economic History ...

  17. R Markdown senior thesis template

    R Markdown, which is really just Markdown with the ability to add in R code and output directly, allows you to produce HTML, PDF, and even Word documents based on only one Markdown file! The sky is the limit for Markdown! The thesis template will automatically convert the Markdown code

  18. Updated R Markdown thesis template

    In October of 2015, I released an R Markdown senior thesis template R package and discussed it in the blogpost here. It was well-received by students and faculty that worked with it and this past summer I worked on updating it to make it even nicer for students. ... (The generating R Markdown file for this HTML document—saved in the .Rmd ...

  19. 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. ... For help using the R markdown template, stop by the mLab during (virutal ...

  20. GitHub

    Create a New R Markdown document: File -> New File -> R Markdown... then choose 'From template', then choose 'Heidelberg Thesis", and enter index as the Name. Note that this will currently only Knit if you name the directory index at this step. If you're not using RStudio, navigate to an empty directory and then run the following code:

  21. 2 R Markdown basics

    2 R Markdown basics. 2. R Markdown basics. Here is a brief introduction to using R Markdown . Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents and much, much more. R Markdown provides the flexibility of Markdown with the implementation of R input and output. For more details on using R Markdown see http ...

  22. GitHub

    Under the hood, the Reed College LaTeX template (and soon the Reed College Word 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 .

  23. Rmarkdown thesis template for those less familiar with LaTeX : r/unr

    The template I'm offering here is a compromise that lets you write your thesis simply while offering the important features of LaTeX. This template is designed to be used within RStudio, an editor for the R programming language, and compiles to an HTML version that can be read online and a PDF version that is ready for submission.