Executed R - Example

Example of a web page with executed R code
Author

Ludovic Deneuville

1 R

To render files including R code, you have to :

    • example : install.packages(c('rmarkdown', 'dplyr', 'ggplot2'))

1.1 Documentation

2 Cells

To write code cells, the principle is the same as with Python.

Simply replace Python with R between the braces.

2.1 Load packages

A good practice is to load all packages at the beginning.

library(dplyr)
library(ggplot2)
library(leaflet)
Deploy on GitHub pages

Don’t forget to add your libraries into the file called DESCRIPTION at the reposiroty root.

This file is essential to list all needed packages when you run GitHub actions.

2.2 First cell

Imagine you want to draw a spiral.

theta <- seq(0, 8 * pi, length.out = 1000)
r <- 0.5 * theta

data <- data.frame(theta = theta, r = r)
data$x <- data$r * cos(data$theta)
data$y <- data$r * sin(data$theta)

ggplot(data, aes(x, y)) +
  geom_path(color = "darkcyan", linewidth = 1.5)
Figure 1: A wonderfull spiral

You cannot see it in the output code but i add those options at the beginning :

```{r}
#| label: fig-spiral
#| fig-cap: A wonderfull spiral
theta <- seq(0, 8 * pi, length.out = 1000)
r <- 0.5 * theta
...
```

So you can use the label and reference the figure elsewhere:

3 Tabulations

4 Inline code

You can display variable values in text.

ages <- c(20, 25, 30, 40)

The average age is 28.75.

5 Interactive Maps

You can include maps using library Leaflet.

leaflet() %>%
  setView(lng=2.6, lat=46.5, zoom=5) %>%
  addTiles() %>%  
  addMarkers(lng=-1.7419, lat=48.0507, popup="ENSAI")