R Markdown Tips: Code, Images, Comments, Tables, and more

Reading time:
time
min
By:
Ivan Millanes
August 21, 2022

<a href="https://rmarkdown.rstudio.com/" target="_blank" rel="noopener">R Markdown</a> is a format for writing reproducible, dynamic reports with R. The output from R Markdown is a <a href="https://www.markdownguide.org/getting-started/" target="_blank" rel="noopener">markdown</a> file that contains chunks of embedded R code. With R Markdown you can create different types of files: HTML documents, PDFs, Word Documents, slideshows, and more. It's a versatile tool for dynamic reporting in R, but there are some hidden R Markdown tips we'd like to show you.
<blockquote>Curious about Quarto? Get started with our hands-on <a href="https://appsilon.com/r-quarto-tutorial/" target="_blank" rel="noopener">Quarto tutorial for creating interactive markdown docs</a>.</blockquote>
If you are new to R Markdown and want to get started we recommend checking out these resources:
<ul><li style="font-weight: 400;" aria-level="1"><a href="https://rmarkdown.rstudio.com/articles_intro.html" target="_blank" rel="noopener">Introduction to R Markdown</a> by Garret Grolemund</li><li style="font-weight: 400;" aria-level="1"><a href="https://www.rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdf" target="_blank" rel="noopener">R Markdown Cheatsheet</a></li><li style="font-weight: 400;" aria-level="1"><a href="https://rmarkdown.rstudio.com/lesson-1.html" target="_blank" rel="noopener">RStudio Lessons</a></li></ul>
In this post, we will cover different tips and tricks that might help you when writing an R Markdown document.

TOC:
<ul><li><a href="#rstudio">Creating an RStudio Project</a></li><li><a href="#posit">RStudio’s Visual Markdown Editor</a></li><li><a href="#code">Tips for Using Code</a></li><li><a href="#comments">Tips for Adding Comments</a></li><li><a href="#images">Tips for Inserting Images</a></li><li><a href="#math">Tips for Mathematics</a></li><li><a href="#table">Tips for Inserting Tables</a></li></ul>

<hr />

<h2 id="rstudio">Creating an RStudio Project</h2>
If you are using RStudio, you should set up an <a href="https://support.rstudio.com/hc/en-us/articles/200526207-Using-RStudio-Projects" target="_blank" rel="noopener">RStudio Project</a> in the directory where you will create your RMarkdown file. In this directory, you will store all the files related to the document you will write.

One of the benefits of RStudio Projects is that you can work using relative paths to the files you store there without the need to manually define working directories.

Throughout the rest of this section, we will assume that you are using an RStudio Project. We recommend exploring Hadley's R4DS to learn more about RStudio Projects and workflows.
<h2 id="posit">RStudio's (Posit) Visual Markdown Editor</h2>
Starting with <a href="https://www.rstudio.com/products/rstudio/download/" target="_blank" rel="noopener">RStudio</a> 1.4, the IDE includes a visual markdown editor that works with both .md and .Rmd files. Visual editing mode allows you to see changes in real-time and preview what your document looks like without re-knitting.

You can enable it by clicking <b>Visual </b>on the top left corner of the document (or using the shortcut Ctrl+Shift+F4). Let’s compare the default (Source) and the editing mode (Visual):

<img class="size-full wp-image-15222" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d761acc439bc258b14a_default-source-markdown-editor.webp" alt="default source markdown editor" width="1044" height="663" /> Default (source) markdown editor

And here is the editing mode (Visual):

<img class="size-full wp-image-15224" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d7744295a0f3322bb69_editing-mode-visual-markdown-editor.webp" alt="editing mode visual markdown editor" width="1071" height="772" /> Editing mode (visual) markdown editor

If you want to learn more about RStudio’s Visual Markdown Editor you can read the following resources:
<ul><li style="font-weight: 400;" aria-level="1"><a href="https://www.rstudio.com/blog/exploring-rstudio-visual-markdown-editor/" target="_blank" rel="noopener">Exploring RStudio’s Visual Markdown Editor</a></li><li style="font-weight: 400;" aria-level="1"><a href="https://rstudio.github.io/visual-markdown-editing/" target="_blank" rel="noopener">Visual R Markdown</a></li></ul>
RStudio has extensive documentation. We highly recommend you explore their resources and become an RStudio product expert!
<h2 id="code">Tips for Using Code in R Markdown</h2>
As mentioned, an R Markdown file contains both text and code. There are two ways to include R code into an R Markdown document: <i>code chunks</i> and <i>inline</i>.
<h3>Code Chunks</h3><ul><li style="font-weight: 400;" aria-level="1">Start with ```{r} and end with ```.</li><li style="font-weight: 400;" aria-level="1">Inside them, you can write any amount of lines.</li><li style="font-weight: 400;" aria-level="1">Inside {} you can define <a href="https://yihui.org/knitr/options/" target="_blank" rel="noopener">chunk options</a>.</li><li style="font-weight: 400;" aria-level="1"><b>TIP</b>: You can add a code chunk using the shortcut Ctrl+Alt+I.</li></ul>
There's plenty more to learn about code chunks!
<h3>Chunk Options</h3>
I've included a list of commonly used chunk options. There's lots more to discover though so be sure to check other options. 

<img class="alignnone wp-image-15273" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d782829666b590b383d_r-markdown-tips-for-code-chunks-table.webp" alt="" width="500" height="310" />
<h3>Inline R Code</h3><ul><li style="font-weight: 400;" aria-level="1">Embedded inside the narratives of the document.</li><li style="font-weight: 400;" aria-level="1">Created using `r `</li></ul>
<h3>Examples of Code in R Markdown</h3>
Let’s take a look at both ways of including R code in our document. 

First, we will print the first few rows of mtcars using different chunk options. Then we will compute the number of rows for that dataset using inline R code.
<pre><code>---
title: "R Markdown Tips and Tricks"
output: html_document
---
<br>This is plain text. Here you place the narrative of the document.</code></pre>
We will now create a code chunk without chunk options.

<pre><code>```{r}
mtcars |&gt;
head()
```
</code></pre>

Next, let's add some options to the same code.
<h4>Hide code using 'echo=FALSE'</h4>
<pre><code>```{r echo=FALSE}
mtcars |&gt;
head()
```</code></pre>
<h4>Hide output using 'eval=FALSE'</h4>
<pre><code>```{r eval=FALSE}
mtcars |&gt;
head()
```
</code></pre>

Finally, let's use some inline R code.

'mtcars' has 'r nrwo(mtcars)' rows.

This is how the output looks:

<img class="alignnone size-full wp-image-15234" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d7a2c0cf4fd2c964d5e_r-code-in-r-markdown.webp" alt="r code in r markdown" width="1401" height="828" />

<img class="alignnone size-full wp-image-15226" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d7a4cedf11e5f974b54_inline-r-code-in-r-markdown.webp" alt="" width="1381" height="231" />
<h2 id="comments">Tips for Adding Comments in R Markdown</h2>
You can comment lines in R Markdown enclosing them with <!--  -->.
<pre><code>---
title: "R Markdown Tips and Tricks"
output: html_document
---
<br>&lt;!-- This line is commented, won't show in the document --&gt;
<br>This line is not commented.</code></pre>
<img class="alignnone size-full wp-image-15260" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d7b508cc5c23320d2f2_tip-for-comment-lines-in-r-markdown-1.webp" alt="" width="1320" height="146" />

<strong>Bonus tip</strong>: Insert comments using the shortcut 'Ctrl+Shift+C'

<img class="alignnone size-full wp-image-15228" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d7d115f687704a6b732_insert-code-and-comments-tips.gif" alt="" width="1600" height="730" />

<strong>Bonus tip</strong>: When commenting code chunks, remember to start in the line above the beginning of the code chunk and end in the line below it.
<h2 id="images">Tips for Inserting Images in R Markdown</h2>
<h3>Using Markdown Syntax</h3>
To add an image to an RMarkdown file you can use the following markdown syntax:

<code> ![Caption for the image](path/to/image.png) </code>

For example, let’s save an image called rmarkdown_hex.png in a folder called img. Remember that you should have created an RStudio Project in the directory where the .Rdm file is. This is how you would add that image to the report:
<pre><code>---
title: "R Markdown Tips and Tricks"
output: html_document
---
<br>This example shows how to include an image in the document.
<br>![This is the caption!](img/rmarkdown_hex.png)
<br>Don't forget to separate the text before and after the image with an empty line!</code></pre>
And once you Knit the file, this is how the output looks:
<img class="alignnone size-full wp-image-15236" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d7e3a154c0fa974215d_r-markdown-tip-for-adding-image-to-output.webp" alt="adding image in r markdown output" width="1397" height="571" />
As you see, we have an empty line between the image syntax and the text. This is what would have happened if we hadn’t added the empty lines:
<pre><code>---
title: "R Markdown Tips and Tricks"
output: html_document
---
<br>This example shows how to include an image in the document.
![This is the caption!](img/rmarkdown_hex.png)
This is what happens if you don't separate the lines of text with an empty line!</code></pre>
<img class="alignnone size-full wp-image-15238" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d80099015d6184d6b7c_r-markdown-tip-for-separating-lines.webp" alt="resulting output after not separating lines of text" width="1354" height="403" />
<h3>Tips For Altering Image Size</h3>
You can change the size of an image by adding {width=“VALUE”}. “VALUE” can be either an absolute number (for example, “400”) or a percentage (for example, “50%”).
<pre><code>---
title: "R Markdown Tips and Tricks"
output: html_document
---
<br>You can set options inside `{}`.
<br>![](img/rmarkdown_hex.png){width="50%"}
</code></pre>
<img class="alignnone size-full wp-image-15218" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d81c094bb3c4e86c48d_changing-image-size-tip-in-r-markdown.webp" alt="changing image size in r markdown output" width="1355" height="923" />
<h3>Tips For Using R Code Chunk</h3>
To insert an image, you can also use an R code chunk.
<pre><code>---
title: "R Markdown Tips and Tricks"
output: html_document
---
<br>You can also insert an image using R code:
<br>```{r}
knitr::include_graphics("img/rmarkdown_hex.png")
```
<br>The image looks smaller by default though.
</code></pre>
<img class="alignnone size-full wp-image-15230" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d81cb8cd72a3d43acd7_insert-image-using-r-code-tip.webp" alt="output of inserting image using r code" width="1390" height="442" />

Remember that you can set the parameter echo=FALSE in the code chunk heading to prevent code from appearing in the finished file.
<h3>Code Chunks For Altering Size And Position</h3>
You can change the size and position of an image through parameters in the code chunk heading.
<pre><code>---
title: "R Markdown Tips and Tricks"
output: html_document
---
<br>You can change the size and position of an image through parameters in the code chunk heading.
<br>```{r echo=FALSE, out.width = "30%", fig.align = "center"}
knitr::include_graphics("img/rmarkdown_hex.png")
```
<br>Here we defined an `out.width = "30%"` and `fig.align = "center"`. We also prevented the code from appearing using `echo=FALSE`.
</code></pre>
<img class="alignnone size-full wp-image-15242" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d8394ab187560d92c7d_tip-for-size-and-positioning-of-images-in-r-markdown.webp" alt="output after resizing and repositioning r markdown image" width="1328" height="659" />
<h3>Using RStudio’s Visual Markdown Editor To Add Images</h3>
There are several ways to include an image using <a href="https://www.rstudio.com/blog/exploring-rstudio-visual-markdown-editor/" target="_blank" rel="noopener">RStudio’s Visual Markdown Editor</a>. In this section, we will explore a few of them:
<h4><strong>Drag and Drop Images</strong></h4>
You can drag an image and drop it in the document.

<img class="alignnone size-full wp-image-15252" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d843e47f6a3572ec1e6_visual-markdown-editor-tips.gif" alt="" width="1600" height="730" />
<h4><strong>Insert Image With GUI</strong></h4>
You can insert an image using the GUI. This is a quick and straightforward method if you prefer to click-to-insert.

You can either click on the picture to access this feature or click 'Insert' -> 'Figure' / 'Image'.

<img class="alignnone size-full wp-image-15220" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d865061b4ab5430e035_click-to-insert-image-or-figure.gif" alt="" width="1600" height="730" />
<h4><strong>Modifying Image Size</strong></h4>
You can modify an image’s size by clicking on the image and changing the values.

<img class="alignnone size-full wp-image-15232" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d86feabe8f16c31891c_modify-image-size-in-visual-markdown-editor.gif" alt="" width="1600" height="730" />
<h2 id="math">Tips for Mathematics in R Markdown</h2>
Sometimes you are writing a report that requires you to insert mathematical symbols alongside greek letters. Fortunately, this can be done in R Markdown!

There are two ways to include mathematics in R Markdown:
<ul><li style="font-weight: 400;" aria-level="1">Inline. Use mathematical notation by wrapping text with dollar signs ($).</li><li style="font-weight: 400;" aria-level="1">Displayed equations. If you use $$ the equation will display in its own line.</li></ul>
Let’s see an example!
<pre><code>---
title: "R Markdown Tips and Tricks"
output: html_document
---
<br>This equation will display inline $\hat{y} = \hat{\beta_0} + \hat{\beta_1} x_1$. You can continue to write as usual.
<br>On the other hand, this equation $$\mu = 30$$ will display in its own line.
</code></pre>
<img class="alignnone size-full wp-image-15248" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d88fb45e346e0b26879_tips-for-mathematical-symbols-in-r-markdown.webp" alt="mathematical symbol output" width="1228" height="354" />

In the example we included:
<ul><li style="font-weight: 400;" aria-level="1">Greek symbols (\beta and \mu).</li><li style="font-weight: 400;" aria-level="1">Subindices (through the use of an underscore _)</li><li style="font-weight: 400;" aria-level="1">Special math symbols (\hat{})</li></ul>
You can find more information about this topic in the following resources:
<ul><li style="font-weight: 400;" aria-level="1"><a href="https://rpruim.github.io/s341/S19/from-class/MathinRmd.html" target="_blank" rel="noopener">Mathematics in R Markdown</a></li><li style="font-weight: 400;" aria-level="1"><a href="https://bookdown.org/fmcron/Rhodes-template/math-expressions.html" target="_blank" rel="noopener">Math expressions</a></li></ul>
<h2 id="table">Tips for Inserting Tables</h2>
In R Markdown you can also insert tables. There are several ways to do this.
<h3>Tips For Inserting Tables With Code Chunks</h3>
You can include tables using different packages. For example:
<pre><code>
---
title: "R Markdown Tips and Tricks"
output: html_document
---
<br>This is a table:
<br>```{r warning=FALSE, message=FALSE, echo=FALSE}
library(knitr)
mtcars |&gt;
 head(5) |&gt;
 kable(caption = "Table built with kable")
```
<br>This is another table:
<br>```{r warning=FALSE, message=FALSE, echo=FALSE}
library(gt)
mtcars |&gt;
 head(5) |&gt;
 gt(caption = "Table built with gt")
```
<br>The tables presented above were built using different packages.
</code></pre>
<img class="alignnone size-full wp-image-15244" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d8800b05468d71a942b_tip-using-code-chunks-to-insert-tables-in-r-markdown.webp" alt="Table output after using code chunks to insert tables in r markdown" width="1400" height="967" />

The first table was built using knitr::kable function. You can further customize how the table looks. Follow <a href="https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html">this</a> link to learn more about knitr::kable!

The second table was built using gt. If you want to know more about this awesome package, <a href="https://gt.rstudio.com/articles/intro-creating-gt-tables.html" target="_blank" rel="noopener">here</a> is a good place to start!
<h3>Using LaTeX (PDF Output Only)</h3>
You can use <a href="https://es.overleaf.com/learn/latex/Creating_a_document_in_LaTeX" target="_blank" rel="noopener">LaTeX</a> syntax in R Markdown. This works only when output: pdf_document.
<pre><code>
---
title: "R Markdown Tips and Tricks"
output: pdf_document
---
<br>Let's create a table using LaTeX!
<br>Remember that this will only output when you are creating a PDF.
<br>\begin{center}
\begin{tabular}{|c c c c|}
\hline
Col1 &amp; Col2 &amp; Col2 &amp; Col3 \\ [0.5ex]
\hline
1 &amp; 6 &amp; 87837 &amp; 787 \\
\hline
2 &amp; 7 &amp; 78 &amp; 5415 \\
\hline
3 &amp; 545 &amp; 778 &amp; 7507 \\
\hline
4 &amp; 545 &amp; 18744 &amp; 7560 \\
\hline
5 &amp; 88 &amp; 788 &amp; 6344 \\ [1ex]
\hline
\end{tabular}
\end{center}
</code></pre>
<img class="alignnone size-full wp-image-15257" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d89115f687704a6c0f3_using-LaTeX-in-r-markdown-for-PDFs.webp" alt="" width="1190" height="480" />

More information can be found in the following resources:
<ul><li style="font-weight: 400;" aria-level="1"><a href="https://es.overleaf.com/learn/latex/Tables" target="_blank" rel="noopener">Tables in LaTeX</a></li></ul>
<h3>Using the GUI to Insert Tables</h3>
Sometimes you want to insert simple tables with text rather than display rows of a dataset. There is a quick and easy way to do this using the GUI.

<img class="alignnone size-full wp-image-15246" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01d8a01b35db453ad6817_tip-using-GUI-to-insert-tables.gif" alt="inserting tables using the GUI" width="1600" height="615" />

Under the hood, this creates the following code:
<pre><code>---
title: "R Markdown Tips and Tricks"
output: html_document
---
<br>Let's add a table with the GUI
<br>| Column 1 | Col2 |
|----------|------|
| Cell 1   |      |
|          |      |
|          |      |
|          |      |
<br>: My Table
</code></pre>
Bonus tip: Most find it easier to use the GUI.
<h2>Conclusion</h2>
In this blog post, we discussed some tips and tricks for writing R Markdown documents. We covered inserting comments, images, and tables using various methods. With Quarto launched, we recommend exploring the next-gen version of R Markdown from RStudio (Posit). It can be used with Python, R, Julia, and Observable.

If you're interested in trying out Quarto for yourself, start with our introduction to R Quarto. If you're more inclined to Python, check out our tutorials on using Quarto and Jupyter Notebooks or Quarto reporting in VS Code. 

As a wrap-up, here's the list of tips:
<ul><li style="font-weight: 400;" aria-level="1">Use RStudio Projects</li><li style="font-weight: 400;" aria-level="1">RStudio’s visual mode</li><li style="font-weight: 400;" aria-level="1">Insert code chunks using shortcuts and explore chunk options</li><li style="font-weight: 400;" aria-level="1">Insert comments using shortcuts</li><li style="font-weight: 400;" aria-level="1">Insert and resize images</li><li style="font-weight: 400;" aria-level="1">Use of mathematics</li><li style="font-weight: 400;" aria-level="1">Insert tables</li></ul>
What are your favorite R Markdown tips? Let us know on <a href="http://twitter.com/appsilon" target="_blank" rel="noopener">Twitter</a> or comment below!

Have questions or insights?

Engage with experts, share ideas and take your data journey to the next level!

Is Your Software GxP Compliant?

Download a checklist designed for clinical managers in data departments to make sure that software meets requirements for FDA and EMA submissions.
Explore Possibilities

Share Your Data Goals with Us

From advanced analytics to platform development and pharma consulting, we craft solutions tailored to your needs.

Talk to our Experts
r
quarto
markdown