DCU R Tutorials

An interactive introduction to R that runs in your browser

Author

Damien Dupré, DCU Business School

Each grey box on this page is a real R console. You can type in it, change the code, and run it. R itself (a version called webR) has been compiled to run inside your web browser, so there is nothing to install, no account to create, and no server to connect to.

A few things worth knowing before you start:

The first time you run a box, R needs a few seconds to start up and download a couple of packages. That only happens once, so please be patient.

Getting started

Let us check that everything is working. Just press Run Code on the box below.

If [1] "Hello World" appeared underneath, then R is running in your browser and you are ready to go.

Chapter 1: WaRm up

R makes a very good calculator, and that is a good place to begin. This chapter covers the pieces you will reach for again and again: objects, functions, vectors, and data frames. You do not need any extra package here, since all of this is part of base R.

Objects and functions

A function does something with the values you put between its brackets. Those values are called its arguments. The assignment arrow <- stores a result in an object so you can use it again later. In each exercise below, replace every ______ using the values described in the comments.

  • seq(from = 5, to = 20) produces 5, 6, 7, up to 20.
  • After my_seq <- seq(1, 10), the object my_seq is the vector 1:10.
  • Anything you store with <- can be reused later by typing its name.
# 1. A sequence from 5 to 20 seq(from = 5, to = 20) # 2. Store seq(1, 10), then multiply by 2 my_seq <- seq(1, 10) my_seq * 2 # 3. Store 2, then multiply the two objects together val_two <- 2 my_seq * val_two
# 1. A sequence from 5 to 20
seq(from = 5, to = 20)

# 2. Store seq(1, 10), then multiply by 2
my_seq <- seq(1, 10)
my_seq * 2

# 3. Store 2, then multiply the two objects together
val_two <- 2
my_seq * val_two

Vectors

A vector is an ordered collection of values, which you build with c(). To pull values out of it you use square brackets [ ], and R counts from 1.

  • Text must go in quotes, like "Connacht". Numbers do not.
  • me[1] is the first element and me[3] is the third.
  • The four provinces are Connacht, Leinster, Munster, and Ulster.
me <- c(25, 170, 9) age <- me[1] shoe <- me[3] age - shoe provinces <- c("Connacht", "Leinster", "Munster", "Ulster") nchar(provinces)
me <- c(25, 170, 9)

age  <- me[1]
shoe <- me[3]
age - shoe

provinces <- c("Connacht", "Leinster", "Munster", "Ulster")
nchar(provinces)

Data frames

A data frame is just a table, with variables in columns and observations in rows. When you use square brackets on a data frame, remember the order: row first, then column.

  • The object is called leinster, so you would write str(leinster).
  • Kildare is the 3rd row, and population is the 3rd column.
  • leinster$population[3] and leinster[3, 3] should give the same number.
leinster <- data.frame( name = c("Carlow", "Dublin", "Kildare", "Kilkenny"), size = c(896, 921, 1693, 2061), population = c(56932, 1347359, 222504, 99232) ) str(leinster) head(leinster) leinster$population[3] leinster[3, 3]
leinster <- data.frame(
  name       = c("Carlow", "Dublin", "Kildare", "Kilkenny"),
  size       = c(896, 921, 1693, 2061),
  population = c(56932, 1347359, 222504, 99232)
)

str(leinster)
head(leinster)

leinster$population[3]

leinster[3, 3]

Chapter 2: Data transformation with dplyr

Now for some real data. From here on we will use the gapminder dataset, which records life expectancy, population, and GDP per capita for most countries between 1952 and 2007. We read it straight from the web and reshape it with the dplyr package, one of the core tidyverse packages.

Run the box below to load the data and take a first look.

The columns are country, continent, year, lifeExp, pop, and gdpPercap.

Filter rows and select columns

filter() keeps the rows that meet a condition, and select() keeps the columns you name. The first argument of every dplyr verb is the data frame you are working on.

  • One hundred million is written 100000000 (or 1e8), with no commas in R.
  • Inside dplyr verbs you write column names without quotes, like country and lifeExp.
filter(gapminder, year == 2007 & pop > 100000000) select(gapminder, country, lifeExp)
filter(gapminder, year == 2007 & pop > 100000000)

select(gapminder, country, lifeExp)

Summarise groups with the pipe

The pipe |> takes the result on its left and passes it into the function on its right, so a chain of steps reads from top to bottom. Together with group_by() and summarise(), it answers questions like “what is the average life expectancy on each continent?”.

  • Filter to year == 2007, group by continent, then take the mean() of lifeExp.
  • It can help to read the pipe |> as the words “and then”.
gapminder |> filter(year == 2007) |> group_by(continent) |> summarise(mean_lifeExp = mean(lifeExp))
gapminder |>
  filter(year == 2007) |>
  group_by(continent) |>
  summarise(mean_lifeExp = mean(lifeExp))

Chapter 3: Visualisation with ggplot2

ggplot2 builds a plot one layer at a time. You start from the data, map variables to things you can see (the x position, the y position, the colour, and so on) with aes(), and then add a geometry such as geom_point() to actually draw them.

  • Map gdpPercap to x, lifeExp to y, and continent to colour.
  • The rest of the plot is already written, so you only need the three aesthetics.
gapminder |> filter(year == 2007) |> ggplot(aes(x = gdpPercap, y = lifeExp, colour = continent)) + geom_point(size = 2, alpha = 0.7) + scale_x_log10() + labs( title = "Wealth and health across the world, 2007", x = "GDP per capita (log scale)", y = "Life expectancy (years)", colour = "Continent" ) + theme_minimal()
gapminder |>
  filter(year == 2007) |>
  ggplot(aes(x = gdpPercap, y = lifeExp, colour = continent)) +
  geom_point(size = 2, alpha = 0.7) +
  scale_x_log10() +
  labs(
    title  = "Wealth and health across the world, 2007",
    x      = "GDP per capita (log scale)",
    y      = "Life expectancy (years)",
    colour = "Continent"
  ) +
  theme_minimal()

Where to go next

You have just filtered, summarised, and plotted real data without installing anything on your machine. There is of course a lot more to R than this, and the only way to get comfortable with it is to keep writing and running code.

If you would like the longer version of this course, the original one (which runs on a server) is at dcu-r-tutorials. The same ideas in Python are in the Python live tutorials.

One last thing: every box on this page keeps your edits for as long as the tab is open, so do feel free to experiment. If you want the original code back, press Start Over on the exercise.