tidy_pipeline.R in R
A full tidyverse pipeline: wrangle, summarize, and plot.
#!/usr/bin/env Rscript
# A full tidyverse pipeline: wrangle, summarise, and plot mtcars.
suppressPackageStartupMessages({
library(dplyr)
library(tidyr)
library(ggplot2)
})
cars <- mtcars %>%
as_tibble(rownames = "model") %>%
mutate(
cylinders = factor(cyl),
transmission = if_else(am == 1, "manual", "automatic"),
efficiency = case_when(
mpg < 15 ~ "thirsty",
mpg < 25 ~ "average",
TRUE ~ "efficient"
)
)
summary_table <- cars %>%
group_by(cylinders, transmission) %>%
summarise(n = n(), avg_mpg = round(mean(mpg), 1), .groups = "drop") %>%
pivot_wider(names_from = transmission, values_from = c(n, avg_mpg))
print(summary_table)
plot <- ggplot(cars, aes(x = wt, y = mpg, colour = cylinders)) +
geom_point(size = 3) +
geom_smooth(method = "lm", se = FALSE, linewidth = 0.6) +
labs(title = "Efficiency by weight", x = "Weight", y = "MPG") +
theme_minimal()
ggsave("efficiency.png", plot, width = 7, height = 5, dpi = 150)
cat("wrote efficiency.png\n")
How it works
mutatewithcase_whenderives labeled columns.group_by/summarizethenpivot_widerbuild a table.ggplotplots it andggsavewrites the figure.
Keywords and builtins used here
aesas_tibbleccase_whencatfactorgeom_pointgeom_smoothggplotggsavegroup_byif_elselabslibrarymeanmutatenpivot_widerprintroundsummarisesuppressPackageStartupMessagestheme_minimal
The run, in numbers
- Lines
- 36
- Characters to type
- 956
- Tokens
- 225
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 123 seconds.
Step 1 of 1 in Encore, step 27 of 27 in dplyr.