10. Introduction to rmarkdwon

Foreword on working directory, data and packages

The Data for this tutorial are provided via Github. In order to reproudce the code with your own data, replace the url with your local filepath

If you work locally, you may define the working directory

# this will not work. if you want to use it, define a path on your computer

This should be the place where your data and other folders are stored. more Information can be found here

Code chunks for saving data and results are disabeled in this tutorial (using a #). Please replace (“YOUR/FILEPATH”) with your own path.

The code is written in such a way, that packages will be automatically installed (if not already installed) and loaded. Packages will be stored in the default location of your computer.


Using rmarkdown you can reproduce your r code and export the results as a report in various formats (html, word, pdf). First, you need to create a markdown file (.rmd). This can be done by clicking file -> New document –> and the selecting R Markdown. Then you add your code plus additional Information. Alternatively you open an existing .rmd file.

R Studio offers a good cheat sheet to get started.

Load the rmarkdown package

if (!require(rmarkdown)){install.packages("rmarkdown"); library(rmarkdown)}

Basic syntax or inline formatting

rmarkdown as a number of expressions that define the basic structure of the document:

Use an asterisk (*) for emphasis, such as italics or double asterisk for bold.

Tildes (~) turn text to a subscript, for example useful when writing chemical formulas: CO2, NO2, H3PO4.

Inline code can be highlighted by usage of backticks: There were nrow(cars) cars studied. It will return the number of rows of the dataset cars.

Hyperlinks can be inserted by usage of the following syntax: [linked phrase](http://example.com).

Images are loaded similarily. Simply add an exclamation mark. Be careful with backslashes and add the file format of the image. Images can bes stored locally or on the web.

![Example of a local image]((https://www.fossgis.de/w/images/thumb/3/3a/Entwurf_fossgis2020-sticker-rund.png/600px-Entwurf_fossgis2020-sticker-rund.png)

Example of a web image

Example of a web image

Images from URL not possible when using Latex -_> Downlad image instead and load from local Folder.

For footnotes use square brackets after a caret ^[], e.g. this example 1. The footnote also works as a hyperlink.

Block level elements


The hashtag # at the beginning of a line implements a header. The number of hashtags also defines the level of the header; one being a first order header, two for second order headers etc. To exclude the number from the header (as in H3-H6), add {-} to header.







Unordered lists can be started with *, -, or +. Through indenting, one list can be nested in another.

  • one item
  • one item
  • one item
    • one more item
    • one more item
    • one more item

Ordered lists start with numbers and may also be nested through indenting.

  1. the first item
  2. the second item
  3. the third item
    • unordered item
    1. sub item


To start quotes, use the > sign:

“Without a systematic way to start and keep data clean, bad data will happen.”

— Donato Diorio


Markdown does not provide any special syntax for tables . Instead, HTML syntax is used. Simple tables separate columns with the | symbol and headers from content cells with the --- symbols.

First Header Second Header
Content Cell Content Cell
Content Cell Content Cell

To create nicely looking tables, it is easiest to use a table generator. Here you can customize your table as you would in Excel. Then you can copy and paste the generated code to yor markdwon file:

R-Package Dependencies

Math expressions

Math expressions such as formulas can be written by using the LaTeX syntax. It is started by a pair of dollar signs. LaTex is an open source typesetting system. It is somewhat similar to markdown but with arguably more complex capabilities to convert plain text files into high-quality documents. Since we will not use LaTex in this course, only this brief introduction and a couple of examples for Latex’s math mode are given:

Square root $\sqrt{x+y}$

Integral $\int\limits^{b}_{a} f(x) dx$

Greek letters $\pi \Phi \varepsilon$

Including your r code

The possibility of including your R code in a markdown document is a very powerful option and the main reason why we use it. You can turn yor analysis in r into high quality documents, reports or even presentations. The documents (and therefore your produced text output, tables, or graphics) are fully reproducible which is also very important when communicating your code or results.

You can simply embed your r code in in a markdwon document and it will be executed. You simply need to tell RStudio that the following chunk is to be treated as R code. This is done by using ``` in between curly braces and by specifying that r sytax is used.


End the code chunk with ```. In between you can insert your r code:

There are a lot of things you can do in a code chunk: you can produce text output, tables, or graphics. You have fine control over all these output via chunk options, which can be provided inside the curly braces. This is in order to modify the output of the document. By default, the code, all outputs in the console and the viewer will be included in the markdown document:

# plot simple map of the happy planet index from the data of the tmap package
if (!require(tmap)){install.packages("tmap"); library(tmap)}
## Lade nötiges Paket: tmap
## Warning: Paket 'tmap' wurde unter R Version 3.6.3 erstellt
## Classes 'sf' and 'data.frame':   177 obs. of  16 variables:
##  $ iso_a3      : Factor w/ 177 levels "AFG","AGO","ALB",..: 1 2 3 4 5 6 7 8 9 10 ...
##  $ name        : Factor w/ 177 levels "Afghanistan",..: 1 4 2 166 6 7 5 56 8 9 ...
##  $ sovereignt  : Factor w/ 171 levels "Afghanistan",..: 1 4 2 159 6 7 5 52 8 9 ...
##  $ continent   : Factor w/ 8 levels "Africa","Antarctica",..: 3 1 4 3 8 3 2 7 6 4 ...
##  $ area        :Object of class units:
##  num  652860 1246700 27400 71252 2736690 ...
##   ..- attr(*, "units")=List of 2
##   .. ..$ numerator  : chr  "km" "km"
##   .. ..$ denominator: chr 
##   .. ..- attr(*, "class")= chr "symbolic_units"
##  $ pop_est     : num  28400000 12799293 3639453 4798491 40913584 ...
##  $ pop_est_dens: num  43.5 10.3 132.8 67.3 15 ...
##  $ economy     : Factor w/ 7 levels "1. Developed region: G7",..: 7 7 6 6 5 6 6 6 2 2 ...
##  $ income_grp  : Factor w/ 5 levels "1. High income: OECD",..: 5 3 4 2 3 4 2 2 1 1 ...
##  $ gdp_cap_est : num  784 8618 5993 38408 14027 ...
##  $ life_exp    : num  59.7 NA 77.3 NA 75.9 ...
##  $ well_being  : num  3.8 NA 5.5 NA 6.5 4.3 NA NA 7.2 7.4 ...
##  $ footprint   : num  0.79 NA 2.21 NA 3.14 2.23 NA NA 9.31 6.06 ...
##  $ inequality  : num  0.427 NA 0.165 NA 0.164 ...
##  $ HPI         : num  20.2 NA 36.8 NA 35.2 ...
##  $ geometry    :sfc_MULTIPOLYGON of length 177; first list element: List of 1
##   ..$ :List of 1
##   .. ..$ : num [1:69, 1:2] 5310471 5408503 5470647 5477147 5541607 ...
##   ..- attr(*, "class")= chr  "XY" "MULTIPOLYGON" "sfg"
##  - attr(*, "sf_column")= chr "geometry"
##  - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA NA NA NA NA NA NA NA NA ...
##   ..- attr(*, "names")= chr  "iso_a3" "name" "sovereignt" "continent" ...
tm_shape(World) +

The ## show the output of the console. readers might not be interested in this information, nor the code youu use. The following commands specify the appearance of your document:

  • include = FALSE prevents code and results from appearing in the finished file. R Markdown still runs the code in the chunk, and the results can be used by other chunks.
  • echo = FALSE prevents code, but not the results from appearing in the finished file. This is a useful way to embed figures.
  • message = FALSE prevents messages that are generated by code from appearing in the finished file.
  • warning = FALSE prevents warnings that are generated by code from appearing in the finished.
  • fig.cap = “…” adds a caption to graphical results.

A full list of chunk options can be found in the R MarkdownReference Guide

Chunk options

Only show results

Options for figures might also be very useful:

Figure: Example of figure generated by R code in rmarkdown with chunk options

Figure 1: Figure: Example of figure generated by R code in rmarkdown with chunk options

Using other languages in R MArkdown

R Markdown supports many other languages such as sql, python and css. Most of the language engines are loaded via the knitr package. A full list of languag engines can be found here.

if (!require(reticulate)){install.packages("reticulate"); library(reticulate)}
use_python("C:/Python27/ArcGIS10.6/python") # depends where you have installed Python
scipy <- import("Numpy")
x <- 42

For a python chunk to be executed we need to specify the location of the python engine. We can use the one that comes with ArcGIS. It may be stored somewhere else on your computer. You may also need to install python first….

`{python}` #x = 42 * 2 #print(x) ` For more info on wheter to chose python over R check the “Data Science Wars: R vs Python”. ——-End——-

  1. This is a footnote.