An RMarkdown file contains several parts. Most essential are the header, the body text, and code chunks.
Body text
The body of the document is where you actually write your reports. This is primarily written in the Markdown format, which is explained in the Markdown syntax section.
The beauty of RMarkdown is, however, that you can evaluate R
code right in the text. To do this, you start inline code with `r, type the code you want to run, and close it again with a `. Usually, this key is below the escape (ESC
) key or next to the left SHIFT button.
For example, if you want to have the result of 48 times 35 in your text, you type ` r 48-35`, which returns 13. Please note that if you return a value with many decimals, it will also print these depending on your settings (for example, 3.1415927).
Code chunks
In the section above we introduced you to running code inside text, but often you need to take several steps in order to get to the result you need. And you don’t want to do data cleaning in the text! This is why there are code chunks. A simple example is a code chunk loading packages.
First, insert a code chunk by going to Code->Insert code chunk
or by pressing CTRL+ALT+I
. Inside this code chunk you can then type for example, library(ggplot2)
and create an object x
.
library(ggplot2)
x <- 1 + 1
If you do not want to have the contents of the code chunk to be put into your document, you include echo=FALSE
at the start of the code chunk. We can now use the contents from the above code chunk to print results (e.g., \(x=2\)).
These code chunks can contain whatever you need, including tables, and figures (which we will go into more later). Note that all code chunks regard the location of the RMarkdown as the working directory, so when you try to read in data use the relative path in.