R Tidyverse Overview
The tidyverse is a popular collection of R packages for data science that share a common design: consistent function names, data frames in and data frames out, and code built from small steps joined with a pipe. Many tutorials and jobs use it, so it's worth knowing what it looks like even though you've learned base R.
Note: The tidyverse packages are not available in this browser playground (it runs base R only), so the tidyverse code in this lesson is shown in plain code blocks. Install them on your own computer with
install.packages("tidyverse"). Every runnable example below is the base R equivalent.
The core packages
| Package | Purpose |
|---|---|
dplyr |
filter, select, mutate, summarise, join data frames |
ggplot2 |
the grammar of graphics: layered, publication-quality charts |
tidyr |
reshape data (wide ↔ long), handle missing values |
readr |
fast reading of CSV and other text files |
tibble |
a modern data frame with nicer printing |
stringr |
consistent string functions (str_detect, str_replace, …) |
forcats |
tools for factors |
purrr |
functional programming (map() and friends) |
lubridate |
easy date handling |
dplyr verbs
dplyr expresses a data manipulation as a sequence of verbs, linked with the pipe (%>% from magrittr, or the native |>):
library(dplyr)
mtcars |>
filter(hp > 100) |>
mutate(kpl = mpg * 0.4251) |>
group_by(cyl) |>
summarise(n = n(), avg_kpl = mean(kpl)) |>
arrange(desc(avg_kpl))The same analysis in base R:
cars <- subset(mtcars, hp > 100)
cars$kpl <- cars$mpg * 0.4251
result <- aggregate(kpl ~ cyl, data = cars,
FUN = function(v) c(n = length(v), avg_kpl = mean(v)))
result <- do.call(data.frame, result)
names(result) <- c("cyl", "n", "avg_kpl")
result[order(-result$avg_kpl), ] cyl n avg_kpl
1 4 2 11.010090
2 6 7 8.392689
3 8 14 6.419010
| dplyr | Base R |
|---|---|
filter(df, cond) |
subset(df, cond) |
select(df, a, b) |
df[, c("a", "b")] |
mutate(df, z = x + y) |
transform(df, z = x + y) |
arrange(df, desc(x)) |
df[order(-df$x), ] |
group_by() + summarise() |
aggregate(), tapply() |
left_join(a, b) |
merge(a, b, all.x = TRUE) |
ggplot2
ggplot2 builds a chart from layers: data, aesthetic mappings (aes), geometric objects (geom_*) and extra settings:
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg, colour = factor(cyl))) +
geom_point(size = 3) +
geom_smooth(method = "lm", se = FALSE) +
labs(title = "Weight vs. fuel economy", x = "Weight (1000 lbs)",
y = "MPG", colour = "Cylinders") +
theme_minimal()A base-graphics version of the same idea:
cols <- c("4" = "tomato", "6" = "seagreen", "8" = "royalblue")
plot(mpg ~ wt, data = mtcars, pch = 19, col = cols[as.character(mtcars$cyl)],
main = "Weight vs. fuel economy", xlab = "Weight (1000 lbs)", ylab = "MPG")
for (k in names(cols)) {
abline(lm(mpg ~ wt, data = subset(mtcars, cyl == as.numeric(k))), col = cols[k])
}
legend("topright", legend = names(cols), col = cols, pch = 19, title = "Cylinders")
sapply(split(mtcars, mtcars$cyl), function(d) round(unname(coef(lm(mpg ~ wt, data = d))[2]), 2)) 4 6 8
-5.65 -2.78 -2.19
tidyr: reshaping
"Tidy" data has one row per observation and one column per variable. pivot_longer() and pivot_wider() convert between wide and long layouts:
library(tidyr)
scores_long <- pivot_longer(scores_wide, cols = c(math, art),
names_to = "subject", values_to = "score")Base R's reshape() does the same, with a less friendly interface:
scores_wide <- data.frame(student = c("Ana", "Ben"), math = c(90, 75), art = c(68, 88))
long <- reshape(scores_wide, direction = "long", varying = c("math", "art"),
v.names = "score", timevar = "subject", times = c("math", "art"),
idvar = "student")
rownames(long) <- NULL
long student subject score
1 Ana math 90
2 Ben math 75
3 Ana art 68
4 Ben art 88
stringr and purrr at a glance
library(stringr)
str_detect(c("apple", "kiwi"), "a") # grepl("a", x)
str_replace_all("a-b-c", "-", "+") # gsub("-", "+", x)
str_to_title("hello world") # tools::toTitleCase()
library(purrr)
map_dbl(mtcars, mean) # vapply(mtcars, mean, numeric(1))
map(split(mtcars, mtcars$cyl), ~ lm(mpg ~ wt, data = .x))Base R or tidyverse?
Both are valid, and most R users mix them. Base R needs no installation and is stable over decades; the tidyverse is more consistent and reads like a recipe. Everything you learned in this course (vectors, data frames, factors, functions, the apply family) is the foundation that the tidyverse is built on.
Test yourself
Which tidyverse package is used for plotting?
- dplyr
- tidyr
- ggplot2
- readr
What is the base R equivalent of filter(df, x > 5)?
- subset(df, x > 5)
- aggregate(df, x > 5)
- order(df, x > 5)
- merge(df, x > 5)
Why aren't tidyverse examples runnable in this course's playground?
- They are deprecated
- Only base R packages are available in the browser playground
- They need Python
- R doesn't support pipes