Skip to content
R

dplyr

Chain mutate, filter, group_by, summarise, and joins with the native pipe.

By EZ4Code Team
dplyrtidyverse

Code

library(dplyr)

set.seed(1)
sales <- tibble(
  region = sample(c("North", "South", "East", "West"), 20, replace = TRUE),
  product = sample(c("A", "B", "C"), 20, replace = TRUE),
  units = sample(1:50, 20, replace = TRUE),
  price = runif(20, 5, 25)
)

# Pipeline of verbs
result <- sales |>
  mutate(revenue = units * price) |>
  filter(units > 10) |>
  group_by(region, product) |>
  summarise(
    total_revenue = sum(revenue),
    avg_units = mean(units),
    n = n(),
    .groups = "drop"
  ) |>
  arrange(desc(total_revenue))
print(result)

# Select and rename
trimmed <- sales |>
  select(region, product, revenue = units) |>
  slice_head(n = 5)
print(trimmed)

# Count
print(count(sales, region, sort = TRUE))

# Join
targets <- tibble(region = c("North", "South"), goal = c(500, 600))
joined <- sales |>
  mutate(revenue = units * price) |>
  group_by(region) |>
  summarise(total = sum(revenue)) |>
  left_join(targets, by = "region") |>
  mutate(met_goal = total >= goal)
print(joined)

Explanation

dplyr provides verbs like filter, mutate, group_by, summarise, and arrange that compose via the native pipe operator |>. Each verb takes and returns a data frame, so pipelines read as a sequence of small transformations. Joins like left_join mirror SQL and integrate cleanly with grouped summaries.

More R Snippets