R Markdown Tips: Code, Images, Comments, Tables, and more
This article is originally published at https://appsilon.com
R Markdown is a format for writing reproducible, dynamic reports with R. The output from R Markdown is a markdown 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.
Curious about Quarto? Get started with our hands-on Quarto tutorial for creating interactive markdown docs.
If you are new to R Markdown and want to get started we recommend checking out these resources:
- Introduction to R Markdown by Garret Grolemund
- R Markdown Cheatsheet
- RStudio Lessons
In this post, we will cover different tips and tricks that might help you when writing an R Markdown document.
TOC:
- Creating an RStudio Project
- Posit’s Visual Markdown Editor
- Tips for Using Code
- Tips for Adding Comments
- Tips for Inserting Images
- Tips for Mathematics
- Tips for Inserting Tables
Creating an RStudio Project
If you are using RStudio, you should set up an RStudio Project 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.
Posit’s Visual Markdown Editor
Starting with RStudio 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 Visual 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):
And here is the editing mode (Visual):
If you want to learn more about RStudio’s Visual Markdown Editor you can read the following resources:
RStudio has extensive documentation. We highly recommend you explore their resources and become an RStudio product expert!
Tips for Using Code in R Markdown
As mentioned, an R Markdown file contains both text and code. There are two ways to include R code into an R Markdown document: code chunks and inline.
Code Chunks
- Start with “`{r} and end with “`.
- Inside them, you can write any amount of lines.
- Inside {} you can define chunk options.
- TIP: You can add a code chunk using the shortcut Ctrl+Alt+I.
There’s plenty more to learn about code chunks!
Chunk Options
I’ve included a list of commonly used chunk options. There’s lots more to discover though so be sure to check other options.
Inline R Code
- Embedded inside the narratives of the document.
- Created using `r `
Examples of Code in R Markdown
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.
---
title: "R Markdown Tips and Tricks"
output: html_document
---
This is plain text. Here you place the narrative of the document.
We will now create a code chunk without chunk options.
```{r}
mtcars |>
head()
```
Next, let’s add some options to the same code.
Hide code using ‘echo=FALSE’
```{r echo=FALSE}
mtcars |>
head()
```
Hide output using ‘eval=FALSE’
```{r eval=FALSE}
Finally, let’s use some inline R code.
mtcars |>
head()
```
‘mtcars’ has ‘r nrwo(mtcars)’ rows.
This is how the output looks:
Tips for Adding Comments in R Markdown
You can comment lines in R Markdown enclosing them with <!– –>.
---
title: "R Markdown Tips and Tricks"
output: html_document
---
<!-- This line is commented, won't show in the document -->
This line is not commented.
Bonus tip: Insert comments using the shortcut ‘Ctrl+Shift+C’
Bonus tip: When commenting code chunks, remember to start in the line above the beginning of the code chunk and end in the line below it.
Tips for Inserting Images in R Markdown
Using Markdown Syntax
To add an image to an RMarkdown file you can use the following markdown syntax:
![Caption for the image](path/to/image.png)
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:
---
title: "R Markdown Tips and Tricks"
output: html_document
---
This example shows how to include an image in the document.
![This is the caption!](img/rmarkdown_hex.png)
Don't forget to separate the text before and after the image with an empty line!
And once you Knit the file, this is how the output looks:
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:
---
title: "R Markdown Tips and Tricks"
output: html_document
---
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!
Tips For Altering Image Size
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%”).
---
title: "R Markdown Tips and Tricks"
output: html_document
---
You can set options inside `{}`.
![](img/rmarkdown_hex.png){width="50%"}
Tips For Using R Code Chunk
To insert an image, you can also use an R code chunk.
---
title: "R Markdown Tips and Tricks"
output: html_document
---
You can also insert an image using R code:
```{r}
knitr::include_graphics("img/rmarkdown_hex.png")
```
The image looks smaller by default though.
Remember that you can set the parameter echo=FALSE in the code chunk heading to prevent code from appearing in the finished file.
Code Chunks For Altering Size And Position
You can change the size and position of an image through parameters in the code chunk heading.
---
title: "R Markdown Tips and Tricks"
output: html_document
---
You can change the size and position of an image through parameters in the code chunk heading.
```{r echo=FALSE, out.width = "30%", fig.align = "center"}
knitr::include_graphics("img/rmarkdown_hex.png")
```
Here we defined an `out.width = "30%"` and `fig.align = "center"`. We also prevented the code from appearing using `echo=FALSE`.
Using RStudio’s Visual Markdown Editor To Add Images
There are several ways to include an image using RStudio’s Visual Markdown Editor. In this section, we will explore a few of them:
Drag and Drop Images
You can drag an image and drop it in the document.
Insert Image With GUI
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’.
Modifying Image Size
You can modify an image’s size by clicking on the image and changing the values.
Tips for Mathematics in R Markdown
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:
- Inline. Use mathematical notation by wrapping text with dollar signs ($).
- Displayed equations. If you use $$ the equation will display in its own line.
Let’s see an example!
---
title: "R Markdown Tips and Tricks"
output: html_document
---
This equation will display inline $\hat{y} = \hat{\beta_0} + \hat{\beta_1} x_1$. You can continue to write as usual.
On the other hand, this equation $$\mu = 30$$ will display in its own line.
In the example we included:
- Greek symbols (\beta and \mu).
- Subindices (through the use of an underscore _)
- Special math symbols (\hat{})
You can find more information about this topic in the following resources:
Tips for Inserting Tables
In R Markdown you can also insert tables. There are several ways to do this.
Tips For Inserting Tables With Code Chunks
You can include tables using different packages. For example:
---
title: "R Markdown Tips and Tricks"
output: html_document
---
This is a table:
```{r warning=FALSE, message=FALSE, echo=FALSE}
library(knitr)
mtcars |>
head(5) |>
kable(caption = "Table built with kable")
```
This is another table:
```{r warning=FALSE, message=FALSE, echo=FALSE}
library(gt)
mtcars |>
head(5) |>
gt(caption = "Table built with gt")
```
The tables presented above were built using different packages.
The first table was built using knitr::kable function. You can further customize how the table looks. Follow this link to learn more about knitr::kable!
The second table was built using gt. If you want to know more about this awesome package, here is a good place to start!
Using LaTeX (PDF Output Only)
You can use LaTeX syntax in R Markdown. This works only when output: pdf_document.
---
title: "R Markdown Tips and Tricks"
output: pdf_document
---
Let's create a table using LaTeX!
Remember that this will only output when you are creating a PDF.
\begin{center}
\begin{tabular}{|c c c c|}
\hline
Col1 & Col2 & Col2 & Col3 \\ [0.5ex]
\hline
1 & 6 & 87837 & 787 \\
\hline
2 & 7 & 78 & 5415 \\
\hline
3 & 545 & 778 & 7507 \\
\hline
4 & 545 & 18744 & 7560 \\
\hline
5 & 88 & 788 & 6344 \\ [1ex]
\hline
\end{tabular}
\end{center}
More information can be found in the following resources:
Using the GUI to Insert Tables
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.
Under the hood, this creates the following code:
---
title: "R Markdown Tips and Tricks"
output: html_document
---
Let's add a table with the GUI
| Column 1 | Col2 |
|----------|------|
| Cell 1 | |
| | |
| | |
| | |
: My Table
Bonus tip: Most find it easier to use the GUI.
Conclusion
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 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:
- Use RStudio Projects
- RStudio’s visual mode
- Insert code chunks using shortcuts and explore chunk options
- Insert comments using shortcuts
- Insert and resize images
- Use of mathematics
- Insert tables
What are your favorite R Markdown tips? Let us know on Twitter or comment below!
The post R Markdown Tips: Code, Images, Comments, Tables, and more appeared first on Appsilon | Enterprise R Shiny Dashboards.
Thanks for visiting r-craft.org
This article is originally published at https://appsilon.com
Please visit source website for post related comments.