dplyr
Chain mutate, filter, group_by, summarise, and joins with the native pipe.
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
Data Frames
Create, inspect, filter, mutate, sort, aggregate, and merge data frames.
Vectors
Build atomic vectors, apply vectorized ops, index, and recycle.
ggplot2
Build layered plots with geoms, facets, and themes using the grammar of graphics.
Statistics
Compute summaries, run t-tests, linear models, ANOVA, and use distributions.
Apply Family
Apply functions over arrays, lists, and groups with apply, lapply, sapply, tapply.
Data Import/Export
Read and write CSV, TSV, RDS, RData, and text files with base R.