Data Wrangling with dplyr and tidyr

Article · 4:00

The pipe, the five verbs that do most of the work, grouped summaries, pivoting between wide and long, and joins.

This is the topic that changes how R feels. dplyr gives you a small set of verbs that each do one thing, and a pipe that chains them so the code reads in the order the work happens.

The pipe. %>% comes from magrittr and arrives with the tidyverse; |> is base R from 4.1 and needs no package. Both take the thing on the left and pass it as the first argument on the right, so data |> filter(x > 1) |> summarise(n = n()) reads left to right. Prefer |> in new code - one fewer dependency, and it is now the default in RStudio's Ctrl+Shift+M. %>% is still everywhere and does a couple of things the native pipe does not, notably . as an explicit placeholder.

The verbs. filter() keeps rows. select() keeps columns. mutate() adds or changes columns. arrange() sorts. summarise() collapses many rows to one. Each takes a data frame and returns a data frame, which is why they chain.

The multiplier is group_by(), which changes what "one" means to the verbs that follow: summarise() after a group_by() returns one row per group instead of one row overall. Modern dplyr prefers the .by argument - summarise(total = sum(x), .by = region) - which groups for that call only and avoids the classic bug of a lingering grouping affecting a later verb.

A detail worth internalising: summarise() drops the last grouping level and tells you so in a message. That message is not noise. Use .groups = "drop" to say what you want and the message goes away.

Pivoting is tidyr's job. Wide data has one row per subject and a column per measurement - good for reading. Long data has one row per observation - which is what ggplot2 and most modelling functions require. pivot_longer() goes wide to long, pivot_wider() goes back. Nearly every "how do I plot these twelve columns" question is really "pivot this longer first".

Joins combine two tables on a key. left_join() keeps every row of the left and is the one you want nine times out of ten. inner_join() keeps only matches. full_join() keeps everything. anti_join() keeps rows of the left with no match, which is the fastest way to find out what failed to join - and checking that is the step people skip before wondering why their row count changed.

library(dplyr)
library(tidyr)

sales <- data.frame(
  region  = c("north", "south", "north", "east", "south", "east"),
  product = c("a", "a", "b", "b", "b", "a"),
  units   = c(10, 25, 8, 14, 30, 5),
  price   = c(2.5, 2.5, 4.0, 4.0, 4.0, 2.5)
)

# ---- The five verbs, chained by the native pipe ----------------------
sales |>
  filter(units > 8) |>                        # rows
  mutate(revenue = units * price) |>          # a new column
  select(region, product, revenue) |>         # columns
  arrange(desc(revenue))                      # sort, biggest first

# select() has helpers worth knowing:
#   select(starts_with("rev"), ends_with("_id"), contains("date"))
#   select(where(is.numeric))
#   select(-product)                 drop one
#   select(area = region)            rename while selecting

# ---- Grouped summaries ----------------------------------------------
sales |>
  mutate(revenue = units * price) |>
  summarise(
    total   = sum(revenue),
    average = mean(revenue),
    n       = n(),                  # n() is the row count of the group
    .by     = region                # modern dplyr: group for THIS call
  )

# The older form, still everywhere:
sales |>
  group_by(region, product) |>
  summarise(total = sum(units), .groups = "drop")
#                                ^^^^^^^^^^^^^^ say what you want, or
#  summarise() drops the LAST grouping level and prints a message about
#  it - and a data frame that is still grouped will silently change what
#  the next verb does.

# Per-group ranking, without collapsing the rows:
sales |>
  mutate(rank = rank(-units), .by = region)

# ---- Wide to long, and back -----------------------------------------
wide <- data.frame(
  country = c("UK", "FR", "DE"),
  y2024   = c(10, 20, 30),
  y2025   = c(12, 22, 35)
)

long <- wide |>
  pivot_longer(
    cols      = starts_with("y"),
    names_to  = "year",
    values_to = "value",
    names_prefix = "y",                # strip the y, leaving 2024
    names_transform = list(year = as.integer)
  )
# country year value
# UK      2024    10
# UK      2025    12   ... one row per observation, which is what
#                          ggplot2 and most model functions want.

long |> pivot_wider(names_from = year, values_from = value)   # and back

# ---- Joins -----------------------------------------------------------
regions <- data.frame(
  region  = c("north", "south", "west"),     # note: no "east"
  manager = c("ada", "grace", "alan")
)

sales |> left_join(regions, by = "region")   # keeps all sales rows;
                                             # east gets manager = NA
sales |> inner_join(regions, by = "region")  # drops east entirely

# The check people skip. What did NOT match?
sales |> anti_join(regions, by = "region")   # the east rows
# Run this BEFORE wondering why the row count changed.

# Different key names on each side:
# left_join(orders, customers, by = c("cust_id" = "id"))

# ---- Missing values --------------------------------------------------
df <- data.frame(x = c(1, NA, 3), y = c("a", "b", NA))

df |> filter(!is.na(x))                 # is.na(), never x == NA
df |> tidyr::drop_na()                  # any NA in any column
df |> tidyr::replace_na(list(x = 0, y = "unknown"))
df |> mutate(x = coalesce(x, 0))        # first non-NA, like SQL

Discussion

No questions on this topic yet. Sign in to ask the first one.