F.2 Getting started

Starting a new R Markdown file is easy: You can either create an .Rmd file from scratch or use a document template.

F.2.1 Creating an .Rmd file

The easiest way to use R Markdown in RStudio is by creating a new R Markdown (.Rmd) file by

  • selecting File > New File > R Markdown (in the RStudio menu),

  • filling in the form (with appropriate entries and selecting html as the desired output format), and

  • saving the resulting file with the .Rmd extension.

Now try to knit your .Rmd file immediately after saving it (by clicking on the wool symbol in the RStudio interface or using the keyboard shortcut Cmd + Shift + K) and — if all goes well — marvel at the beauty of the resulting .html-file. At this point, 2 outcomes are possible:

  1. If knitting is successful, then check your desired outcome file and return to your .Rmd file to make further changes.

  2. If knitting fails to create your desired output file, pay attention to the error message. At the beginning, missing packages, mis-spelled commands, and erroneous R code are the most common sources of errors. If your R code contains errors that you cannot easily fix, a way to still knit your document is to add a eval = FALSE option to the corresponding code chunk(s).76 Selectively setting code chunk options lets you specify which code chunks are shown (or hidden) and evaluated (or ignored, see Section F.3.3 below).

From now on, save and knit your .Rmd document routinely as you keep adding text and code. To advance your project further, write any text — like headings that structure your document, explanations what or why you are doing some analysis, and the meaning of results — outside of any code chunks. By contrast, any R code that creates objects or computes results belongs into code chunks.

Note how important it is to separate input (here: an .Rmd file) from output (here: an .html file): From now on, you can share your HTML outputs, rather than your R scripts or R Markdown sources to show off your R and data science skills. Thus, the recipients of your files no longer need to run R, which drastically increases your potential audience.

F.2.2 Templates

As an alternative to starting a new .Rmd file from scratch, you can use one of the following document templates:

  • minimal template: rmd_template_s [in .Rmd | .html format]

  • medium template: rmd_template_m [in .Rmd | .html format]

  • explicit explanations: Rmarkdown_basics [in .Rmd | .html format]

  1. This only works if later R code does not depend on the current chunk.