Writing your thesis with R Markdown (3) – Figures, R code and tables

This is the third post in a short series of tutorials to write your thesis in R Markdown. You can find instructions on how to get started in the first post. These tutorials were written by a Windows user, so if you are using a different operating system some details may differ.

Welcome back to part three of this tutorial! In the previous post we looked at including text, citations, and equations in the thesis chapter. This time we’ll look at including figures, R code and tables. Let’s start with the figures:

Step 4: Including a figure

You can include a figure in an R Markdown by writing ‘![Figure caption](name_of_figure.jpg)‘ in the document. To make sure a caption shows up underneath your figure, we need to turn on the captions option, as in R Markdown it is turned off by default. You can do this by writing this bit in your YAML header:

    fig_caption: yes

The indentation of the above bit of text is important, knitr will not understand it if it is not written exactly like the above.

To refer to the figure in-text, a label needs to be added to the figure. This can be done by writing: ‘![Figure caption \label{figurelabel}](filename.png)‘ (what you are actually doing here is adding a LaTeX label to Markdown text). Then, if you canwrite, for example, ‘see figure \ref{}‘, or as you may remember from the previous post, ‘see \autoref{}‘.


Left: Adding a figure. Right: .pdf output. Click on image to enlarge.

Note: figures are seen as ‘floats’ by LaTeX, and therefore are not placed immediately where you call them. If you want to get more specific with how to place them and what height and such, I recommend you use latex syntax to include the figure instead of using the R Markdown syntax. You can read more here. I generally did not find it necessary in my thesis, but it requires some playing around to figure out what works best for your thesis.

Step 5: using R code

This is where we get to the real magic of using R Markdown: including R code and data anlaysis directly into your thesis!

Here is how you include R code in your story. It’s called a code chunk:

# some R code

There are a bunch of values you can you give your code chunks. For example, if you don’t want to include code in your text, but just the output, you can write ‘{r include = FALSE}‘. You can also suppress warnings by writing  ‘{r warning = FALSE}‘. If you don’t do this and something is wrong with your code, a warning message might be printed in your thesis. Anyway, there’s a whole list of things you can do with knitr chunks. I only discuss the ones I found necessary here, but if you’re interested, Yihui Xie, the developer of knitr, provides some great documentation on his website.

There are probably some things you want most of your code chunks to do, so you can set your own defaults for your thesis using:

```{r include=FALSE}
knitr::opts_chunk$set(fig.path = 'figures/', echo = FALSE, warning = FALSE, message = FALSE)

Basically what you are saying here is firstly, you want the figures to be saved in the folder ‘figures’, secondly, the R code itself won’t be printed, just the output, thirdly, warning won’t be printed and finally messages (similar to warnings) won’t be printed either.

Note: If you are making rather big calculations in the code chunks, this can make it slow to render your thesis (i.e. knitting). You can cache files with ‘cache=TRUE‘. Note that you will need to turn this off if you want to update your calculations.

One of the great things about including R code directly in your thesis is that you can generate and change figures as you go. To create a figure in your thesis using R code, just write the R code as you would normally when making a figure, for example:

```{r fig.cap = "figure caption. \\label{figurelabel}", fig.height=12, fig.width=10}

As you can see, I’ve added some info to the R code chunk about how to render the figure. I defined a figure caption with ‘fig.cap‘ and added a LaTeX label for in-text reference. Don’t forget to write the double backslash when adding a label name.

You can also refer to stuff in your text, that you calculated inside a code chunk. For example, if the code chunk says:

```{r include = FALSE}
variable_t = 3 * 4

you can refer to that in text by simply writing: `r variable_t`.

Below is image that compares the .rmd file and the .pdf output to show what kind of output each code chunk produces.


Left: Using R code in R Markdown. Right: .pdf output. Click on image to enlarge.

Step 6: Including a table

Sometimes you find yourself needing to include a table. Markdown and kable can do the trick, but I do not recommend using it for ‘serious, thesis-grade’ tables. In a thesis, you will almost always find yourself wanting more flexibility than Markdown and kable can offer. I therefore highly recommend using LaTeX when including tables.

This is some simple LaTeX code for a neat-looking table you might want to use in your thesis:

\begin{tabular}{ p{4cm} p{4cm} p{4cm} }
\hline \\ [-1.5ex]
colname & colname & colname \\ [1ex]
\hline \\ [-1.5ex]
Info & info & info \\ [1ex]
Info & info & info \\ [1ex]
Info & info & info \\ [1ex]

I will not go into great detail about LaTeX tables here, but if you’d like some more information, have a look at this Wiki. If you’re finding LaTeX tables a bit confusing, you can also write your table in excel and then upload it to this website: it will make a LaTeX table for you. Also, I had to use a couple of multi-page tables in my thesis. If you find you need to do the same, have a google search for ‘latex longtable’.

Note: References are note translated to LaTeX, but into plain text. This means that you cannot add any R Markdown references (i.e. [@Author2000]) in a LaTeX table. If you want more information, it got me quite confused as well, so I wrote a question and then an answer about it on tex.stackexchange.com.


Left: Including a LaTeX table. Right: .pdf output. LaTeX automatically places tables at the bottom of the page. Click on image to enlarge.

And that’s it! Of course this is only one chapter, so in the next post we’ll have a look a writing multiple chapter in multiple .rmd files, how to put together and turn it into a pretty thesis. If you have any questions, feel free to post them in the comments or shoot me an email!


6 thoughts on “Writing your thesis with R Markdown (3) – Figures, R code and tables

  1. Pingback: Writing your thesis with R Markdown (4) – Putting the thesis together | Rosanna's Research

  2. Great post. It is true that using latex for tables allows more flexibility, but xtable package is also a good choice specially if you look at the xtable gallerie (it is a pdf document that you can find in searching in google ). xtable is way more powerfull than kable and you dont need to typeset every single value such as in latex.

  3. ![a picture](C:/Users/dell/Desktop/3m.jpg)

    The name of the input file cannot contain the special shell characters: [ ()|\:&;#?*’] (attempted to copy to a version without those characters ‘Chinese_template02.Rmd’ however that file already exists)


  4. Hi,

    Love the blog! I have an issue with the tables, after editting your code so that my text is wrapped around the table. Now my table floats outside the document border! How do I solve that issue?

  5. Pingback: Writing your thesis with R Markdown – paulvanderlaken.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s