Reading — step 1 of 4
Learn
The tidyverse is a collection of packages by Hadley Wickham that defines a consistent grammar for data manipulation. The packages: dplyr (transform), tidyr (reshape), ggplot2 (plot), readr (read), purrr (functional), stringr (strings), forcats (factors), lubridate (dates).
The pipe |> (or %>% from magrittr): x |> f() = f(x). Chain transformations:
library(dplyr)
library(dplyr)
result <- mtcars |>
filter(cyl == 6) |>
mutate(efficiency = mpg / hp) |>
group_by(gear) |>
summarise(avg_eff = mean(efficiency)) |>
arrange(desc(avg_eff))
Reads top-to-bottom: take mtcars, keep 6-cylinder rows, add an efficiency column, group by gear, summarise mean efficiency, sort descending.
Core dplyr verbs:
filter(cond)— keep rows where cond is TRUEselect(cols)— pick columnsmutate(new = expr)— add/modify columnsarrange(col)— sort rows;desc(col)reversesgroup_by(col)+summarise(stat = fn(col))— aggregateslice(n)— pick rows by indexdistinct()— drop duplicatesrename(new = old)— rename columncount(col)— group_by + summarise(n())*_join(other)—inner_join,left_join,right_join,full_join,anti_join
mutate with conditionals:
df |> mutate(
grade = case_when(
score >= 90 ~ "A",
score >= 80 ~ "B",
score >= 70 ~ "C",
TRUE ~ "F"
)
)
Pivot wider/longer (tidyr):
library(tidyr)
# Long format -> wide format
long |> pivot_wider(names_from = quarter, values_from = sales)
# Wide format -> long format
wide |> pivot_longer(cols = q1:q4, names_to = "quarter", values_to = "sales")
Long format is usually what you want for analysis. Wide format is what spreadsheets give you.
ggplot2 — the grammar of graphics:
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point() +
geom_smooth(method = "lm") +
labs(title = "MPG vs Weight by Cylinders", color = "Cyl")
Layer-based: data + aesthetic mappings + geometric layers + scale/theme.
Why tidyverse?
- Consistent: every verb is data-first, returns a data frame, takes column names unquoted
- Pipeable:
|>chains naturally - Documented: each package has comprehensive vignettes
- Active: still evolving with
tidymodels(ML),targets(workflows),arrow(Parquet)
When to skip:
- Tiny scripts where base R is shorter
- Performance-critical code (use
data.table) - Libraries that need minimal dependencies
For analysis work, tidyverse is the dominant idiom — most R job postings list dplyr+ggplot2.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…