Introduction to R Markdown (2024)

Garrett Grolemund

July 16, 2014

Interactive documents are a new way to build Shiny apps. An interactive document is an R Markdown file that contains Shiny widgets and outputs. You write the report in markdown, and then launch it as an app with the click of a button.

This article will show you how to write an R Markdown report.

The companion article, Introduction to interactive documents, will show you how to turn an R Markdown report into an interactive document with Shiny components.

R Markdown

R Markdown is a file format for making dynamic documents with R. An R Markdown document is written in markdown (an easy-to-write plain text format) and contains chunks of embedded R code, like the document below.

---output: html_document---This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see .When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:```{r}summary(cars)```You can also embed plots, for example:```{r, echo=FALSE}plot(cars)```Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

R Markdown files are designed to be used with the rmarkdown package. rmarkdown comes installed with the RStudio IDE, but you can acquire your own copy of rmarkdown from CRAN with the command

install.packages("rmarkdown")

R Markdown files are the source code for rich, reproducible documents. You can transform an R Markdown file in two ways.

  1. knit - You can knit the file. The rmarkdown package will call the knitr package. knitr will run each chunk of R code in the document and append the results of the code to the document next to the code chunk. This workflow saves time and facilitates reproducible reports.

    Consider how authors typically include graphs (or tables, or numbers) in a report. The author makes the graph, saves it as a file, and then copy and pastes it into the final report. This process relies on manual labor. If the data changes, the author must repeat the entire process to update the graph.

    In the R Markdown paradigm, each report contains the code it needs to make its own graphs, tables, numbers, etc. The author can automatically update the report by re-knitting.

  2. convert - You can convert the file. The rmarkdown package will use the pandoc program to transform the file into a new format. For example, you can convert your .Rmd file into an HTML, PDF, or Microsoft Word file. You can even turn the file into an HTML5 or PDF slideshow. rmarkdown will preserve the text, code results, and formatting contained in your original .Rmd file.

    Conversion lets you do your original work in markdown, which is very easy to use. You can include R code to knit, and you can share your document in a variety of formats.

In practice, authors almost always knit and convert their documents at the same time. In this article, I will use the term render to refer to the two step process of knitting and converting an R Markdown file.

You can manually render an R Markdown file with rmarkdown::render(). This is what the above document looks like when rendered as a HTML file.

Introduction to R Markdown (1)

In practice, you do not need to call rmarkdown::render(). You can use a button in the RStudio IDE to render your reprt. R Markdown is heavily integrated into the RStudio IDE.

Getting started

To create an R Markdown report, open a plain text file and save it with the extension .Rmd. You can open a plain text file in your scripts editor by clicking File > New File > Text File in the RStudio toolbar.

Introduction to R Markdown (2)

Be sure to save the file with the extension .Rmd. The RStudio IDE enables several helpful buttons when you save the file with the .Rmd extension. You can save your file by clicking File > Save in the RStudio toolbar.

Introduction to R Markdown (3)

R Markdown reports rely on three frameworks

  1. markdown for formatted text
  2. knitr for embedded R code
  3. YAML for render parameters

The sections below describe each framework.

Markdown for formatted text

.Rmd files are meant to contain text written in markdown. Markdown is a set of conventions for formatting plain text. You can use markdown to indicate

  • bold and italic text
  • lists
  • headers (e.g., section titles)
  • hyperlinks
  • and much more

The conventions of markdown are very unobtrusive, which make Markdown files easy to read. The file below uses several of the most useful markdown conventions.

# Say Hello to markdownMarkdown is an **easy to use** format for writing reports. It resembles what you naturally write every time you compose an email. In fact, you may have already used markdown *without realizing it*. These websites all rely on markdown formatting* [Github](www.github.com)* [StackOverflow](www.stackoverflow.com)* [Reddit](www.reddit.com)

The file demonstrates how to use markdown to indicate:

  1. headers - Place one or more hashtags at the start of a line that will be a header (or sub-header). For example, # Say Hello to markdown. A single hashtag creates a first level header. Two hashtags, ##, creates a second level header, and so on.

  2. italicized and bold text - Surround italicized text with asterisks, like this *without realizing it*. Surround bold text with two asterisks, like this **easy to use**.

  3. lists - Group lines into bullet points that begin with asterisks. Leave a blank line before the first bullet, like this

     This is a list * item 1 * item 2 * item 3
  4. hyperlinks - Surround links with brackets, and then provide the link target in parentheses, like this [Github](www.github.com).

You can learn about more of markdown’s conventions in the Markdown Quick Reference guide, which comes with the RStudio IDE.

To access the guide, open a .md or .Rmd file in RStudio. Then click the question mark that appears at the top of the scripts pane. Next, select “Markdown Quick Reference”. RStudio will open the Markdown Quick Reference guide in the Help pane.

Introduction to R Markdown (4)

Rendering

To transform your markdown file into an HTML, PDF, or Word document, click the “Knit” icon that appears above your file in the scripts editor. A drop down menu will let you select the type of output that you want.

Introduction to R Markdown (5)

When you click the button, rmarkdown will duplicate your text in the new file format. rmarkdown will use the formatting instructions that you provided with markdown syntax.

Once the file is rendered, RStudio will show you a preview of the new output and save the output file in your working directory.

Here is how the markdown script above would look in each output format.

Introduction to R Markdown (6)

Note: RStudio does not build PDF and Word documents from scratch. You will need to have a distribution of Latex installed on your computer to make PDFs and Microsoft Word (or a similar program) installed to make Word files.

knitr for embedded R code

The knitr package extends the basic markdown syntax to include chunks of executable R code.

When you render the report, knitr will run the code and add the results to the output file. You can have the output display just the code, just the results, or both.

To embed a chunk of R code into your report, surround the code with two lines that each contain three backticks. After the first set of backticks, include {r}, which alerts knitr that you have included a chunk of R code. The result will look like this

Here’s some code```rdim(iris)``````## [1] 150 5```

When you render your document, knitr will run the code and append the results to the code chunk. knitr will provide formatting and syntax highlighting to both the code and its results (where appropriate).

As a result, the markdown snippet above will look like this when rendered (to HTML).

Introduction to R Markdown (7)

To omit the results from your final report (and not run the code) add the argument eval = FALSE inside the brackets and after r. This will place a copy of your code into the report.

Introduction to R Markdown (8)

To omit the code from the final report (while including the results) add the argument echo = FALSE. This will place a copy of the results into your report.

Introduction to R Markdown (9)

echo = FALSE is very handy for adding plots to a report, since you usually do not want to see the code that generates the plot.

Introduction to R Markdown (10)

echo and eval are not the only arguments that you can use to customize code chunks. You can learn more about formatting the output of code chunks at the rmarkdown and knitr websites.

Inline code

To embed R code in a line of text, surround the code with a pair of backticks and the letter r, like this.

Two plus two equals 4.

knitr will replace the inline code with its result in your final document (inline code is always replaced by its result). The result will appear as if it were part of the original text. For example, the snippet above will appear like this:

Introduction to R Markdown (11)

YAML for render parameters

You can use a YAML header to control how rmarkdown renders your .Rmd file. A YAML header is a section of key: value pairs surrounded by --- marks, like below

---title: "Untitled"author: "Garrett"date: "July 10, 2014"output: html_document---Some inline R code, 4.

The output: value determines what type of output to convert the file into when you call rmarkdown::render(). Note: you do not need to specify output: if you render your file with the RStudio IDE knit button.

output: recognizes the following values:

  • html_document, which will create HTML output (default)
  • pdf_document, which will create PDF output
  • word_document, which will create Word output

If you use the RStudio IDE knit button to render your file, the selection you make in the gui will override the output: setting.

Slideshows

You can also use the output: value to render your document as a slideshow.

  • output: ioslides_presentation will create an ioslides (HTML5) slideshow
  • output: beamer_presentation will create a beamer (PDF) slideshow

Note: The knit button in the RStudio IDE will update to show slideshow options when you include one of the above output values and save your .Rmd file.

rmarkdown will convert your document into a slideshow by starting a new slide at each header or horizontal rule (e.g., ***).

Visit rmakdown.rstudio.com to learn about more YAML options that control the render process.

Recap

R Markdown documents provide quick, reproducible reporting from R. You write your document in markdown and embed executable R code chunks with the knitr syntax.

You can update your document at any time by re-knitting the code chunks.

You can then convert your document into several common formats.

R Markdown documents implement Donald’s Knuth’s idea of literate programming and take the manual labor out of writing and maintaining reports. Moreover, they are quick to learn. You already know ecnough about markdown, knitr, and YAML to begin writing your own R Markdown reports.

In the next article, Introduction to interactive documents, you will learn how to add interactive Shiny components to an R Markdown report. This creates a quick workflow for writing light-weight Shiny apps.

To learn more about R Markdown and interactive documents, please visit rmarkdown.rstudio.com.

Introduction to R Markdown (2024)

FAQs

Is R Markdown easy to use? ›

This may sound complicated, but R Markdown makes it extremely simple by encapsulating all of the above processing into a single render function. Better still, RStudio includes a “Knit” button that enables you to render an . Rmd and preview it using a single click or keyboard shortcut.

What is the point of R Markdown? ›

Some of the advantages of using R markdown include: Explicitly links your data with your R code and output creating a fully reproducible workflow. ALL of the R code used to explore, summarise and analyse your data can be included in a single easy to read document.

Is R Markdown a coding language? ›

R markdown is a simple and easy to use plain text language used to combine your R code, results from your data analysis (including plots and tables) and written commentary into a single nicely formatted and reproducible document (like a report, publication, thesis chapter or a web page like this one).

What is the difference between R Markdown and Markdown? ›

RMarkdown is an extension to markdown which includes the ability to embed code chunks and several other extensions useful for writing technical reports. See this Rstudio page for a list of all the output formats supported. Behind-the-scenes, the conversions are typically done using pandoc which we will not cover here.

How hard is it to learn Markdown? ›

Formatting text in Markdown has a very gentle learning curve. It doesn't do anything fancy like change the font size, color, or type. All you have control over is the display of the text—stuff like making things bold, creating headers, and organizing lists. If you have ten minutes, you can learn Markdown!

What are the disadvantages of R Markdown? ›

There are a few disadvantages to R Markdown. No track changes - Even if you're lucky to have an advisor who will review a . Rmd file, you won't get nice track changes like in Word. There are alternative to this (version control helps) but not are quite as easy as track changes.

Is Markdown still relevant? ›

Many technical writers either currently use or interested in using Markdown to write their technical documentation. It's a bit like Marmite – some people love it and other people kind of hate it. Markdown generates some controversy, but it still proves incredibly useful in certain contexts.

Is R Markdown better than R Script? ›

R Markdown provides a large number of options to vary the behavior of code chunks. In some contexts it is useful to display the output but not the R code leading to the output. In some contexts it is useful to display the R prompt, while in others it is not.

Is R Markdown better than LaTeX? ›

R Markdown is certainly not the best possible document format for authoring or typesetting documents. Simplicity is both its advantage and disadvantage. LaTeX is much more powerful than Markdown in terms of typesetting at the price of more commands to be typed.

Can I run Python in R Markdown? ›

We know you love Python, so let's make it super clear: R Markdown and knitr do support Python. To add a Python code chunk to an R Markdown document, you can use the chunk header ```{python} , e.g., ```{python} print("Hello Python!") ```

Is there a Python version of R Markdown? ›

The reticulate package includes a Python engine for R Markdown that enables easy interoperability between Python and R chunks. Python chunks behave very similar to R chunks (including graphical output from matplotlib) and the two languages have full access each other's objects.

How do I write codes in R Markdown? ›

Code results can be inserted directly into the text of a . Rmd file by enclosing the code with `r ` . The file below uses `r ` twice to call colorFunc , which returns “heat. colors.” You can open the file here in RStudio Cloud.

What is R Markdown good for? ›

R Markdown provides an unified authoring framework for data science, combining your code, its results, and your prose commentary. R Markdown documents are fully reproducible and support dozens of output formats, like PDFs, Word files, slideshows, and more.

Should I use R Markdown or notebook? ›

R Notebooks are better suited for smaller analyses or exploratory work. R Markdown is better suited for larger-scale projects with more complex requirements.

What is the alternative to R markdown? ›

Alternatives to R Markdown
  • Inkdrop. Inkdrop. $4.16 per month. ...
  • blogdown. blogdown. This book introduces blogdown, an R package that teaches you how to create websites with Hugo and R Markdown. ...
  • Markdown Monster. Markdown Monster. ...
  • StackEdit. StackEdit. ...
  • Quiver. Quiver. ...
  • MWeb. MWeb. ...
  • ghostwriter. ghostwriter. ...
  • Remarkable. Remarkable.

Is Markdown easier than HTML? ›

Markdown is easier to write than HTML, and it's easier for most humans to read Markdown source than HTML source.

Is Markdown easier than LaTeX? ›

Of course, LaTex took me probably the same time initially to get it to run, so here's how I see the decision: Markdown makes it very easy to do very easy things, but getting something more complicated done (like referencing code blocks) can be frustrating and seem impossible.

Is R Markdown like Jupyter Notebook? ›

Just like with Jupyter, you can also work interactively with your R Markdown notebooks. It works a bit differently from Jupyter, as there are no real magic commands; To work with other languages, you need to add separate Bash, Stan, Python, SQL or Rcpp chunks to the notebook.

References

Latest Posts
Recommended Articles
Article information

Author: Velia Krajcik

Last Updated:

Views: 5853

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Velia Krajcik

Birthday: 1996-07-27

Address: 520 Balistreri Mount, South Armand, OR 60528

Phone: +466880739437

Job: Future Retail Associate

Hobby: Polo, Scouting, Worldbuilding, Cosplaying, Photography, Rowing, Nordic skating

Introduction: My name is Velia Krajcik, I am a handsome, clean, lucky, gleaming, magnificent, proud, glorious person who loves writing and wants to share my knowledge and understanding with you.