Programming Languages
R from first script to tidyverse data wrangling, ggplot2, statistics, modelling and spatial work.
A path through R for data analysis: the language and its data structures, importing and cleaning data, the tidyverse, visualisation with ggplot2, dashboards, statistics and modelling, then text, network, spatial and big-data work. For analysts, researchers and developers who want to do serious data work in R. Each subject links the official documentation or the package's own site.
The subjects follow the roadmap.sh R Programming roadmap.
R is a language and environment built by statisticians for data analysis, modelling and graphics. Its strengths are vectorised operations, a huge package ecosystem on CRAN and first-class plotting; its quirks come from being designed for interactive analysis first and programming second.
R shines in statistics, quick exploratory work and publication-quality charts; Python in general software, deep learning and production services. Many teams use both — the tidyverse and pandas/polars solve the same problems with different idioms.
Download R from CRAN for Windows, macOS or Linux (or use rig to manage several versions). R itself is the interpreter; an IDE is installed separately. New minor versions arrive yearly and need packages reinstalled.
Write code in a .R file rather than the console so it can be rerun, run lines with Ctrl/Cmd+Enter, and run the whole file with source() or Rscript file.R from a terminal. Work inside a project so relative paths behave.
A productive R setup is an IDE, a project per analysis, and a reliable way to install and pin packages. Getting this right early prevents "works on my machine" problems when you share code or revisit it months later.
Posit's R-focused IDE: console, editor, environment pane, plots, help and project management in one window, plus integrated Quarto and Git. The default choice for most R users.
Posit's newer data-science IDE built on the VS Code engine, supporting R and Python side by side with a variables pane, data explorer and plots viewer.
Works well for R with the R extension and the languageserver package, especially if you already live in VS Code for other languages. Plot viewing and data inspection are less polished than in RStudio.
install.packages("dplyr") downloads from CRAN into your library; library(dplyr) attaches it for the session. Install once, load every session, and call pkg::fn() to avoid name clashes.
The Comprehensive R Archive Network: the official package repository, with strict checks on every submission. Task Views group packages by field, a good place to find the standard tool for a job.
A faster installer that resolves dependencies up front, installs in parallel and handles CRAN, Bioconductor and GitHub sources with one call: pak::pak("tidyverse/dplyr").
Per-project package libraries with a lockfile. renv::init() isolates a project, renv::snapshot() records exact versions and renv::restore() rebuilds them elsewhere — essential for reproducible analyses.
R reads like a calculator that grew into a language: expressions are evaluated and printed, almost everything is a function call, and most operations work on whole vectors at once. Learn the handful of rules that differ from other languages, such as <- for assignment and 1-based indexing.
Assign with x <- 5; names are case-sensitive and conventionally snake_case. R copies on modify, so changing a value inside a function never alters the caller's object.
Arithmetic (+ - * / ^ %% %/%), comparison, and logical operators. Use vectorised & and | on vectors but && and || in if conditions, which require a single value.
The native pipe |> (R 4.1+) passes the left side as the first argument of the right, turning nested calls into a readable left-to-right chain. The magrittr %>% is the older equivalent with a few extra features.
Everything after # on a line is ignored; there is no block comment syntax. Comment why, not what, and use # ---- Section ---- headers to get a navigable outline in RStudio.
if (cond) { } else { } evaluates one condition; ifelse() and dplyr::if_else() and case_when() work element-wise across vectors. switch() chooses among named alternatives.
for, while and repeat exist, but vectorised functions or the apply/map families are usually clearer and faster. If you loop, preallocate the output with vector("list", n) instead of growing it.
Literate programming mixes prose, code and results in one document that rebuilds from data, so reports never drift out of date. R users render to HTML, PDF, Word, slides, websites and books from the same source.
The current, multi-language successor to R Markdown: .qmd files with YAML options and code chunks, rendered with quarto render to documents, slides, dashboards and full websites.
The original .Rmd format powered by knitr and Pandoc. Still widely used and maintained; existing projects rarely need migrating, but new ones usually start with Quarto.
R has a few atomic types, and every value is a vector of one of them — even a single number is a length-1 vector. typeof() shows the storage type, class() the behaviour; NA exists in every type.
Double-precision floating point, the default for numbers. Compare with all.equal() or a tolerance, not ==, because 0.1 + 0.2 == 0.3 is FALSE.
Whole numbers written with an L suffix (5L) or produced by seq_len() and :. They use less memory and are exact, but overflow to NA beyond about 2.1 billion.
Text strings in single or double quotes, stored as UTF-8 in modern R. Each element of a character vector is a whole string, not a single character.
TRUE, FALSE and NA. Logicals coerce to 1 and 0, so sum(x > 10) counts and mean(x > 10) gives a proportion. Avoid the T and F shortcuts — they can be overwritten.
Numbers with real and imaginary parts, written 3+2i, with Re(), Im(), Mod() and Arg(). Rare outside signal processing and some maths.
Explicit conversion uses the as.*() family (as.numeric, as.character, as.integer); implicit coercion follows logical → integer → double → character when types mix in one vector. Failed conversions return NA with a warning — check for them rather than ignoring the message.
Atomic vectors are one-dimensional and one type; add dimensions and you get matrices and arrays; lists hold anything; data frames are lists of equal-length columns. Knowing which you have tells you how [, [[ and $ will behave.
Created with c(), indexed from 1, and operated on element-wise. Shorter vectors are recycled to match longer ones, which is handy for scalars and a silent bug otherwise.
Ordered containers of any objects, including other lists — the basis for model results and JSON-like data. [ returns a sub-list, [[ or $ returns the element itself.
Two-dimensional vectors of one type, built with matrix(), rbind() or cbind(). %*% does matrix multiplication and t() transposes; [i, j] drops to a vector unless drop = FALSE.
Matrices generalised to any number of dimensions with array(data, dim = c(...)). Useful for image or simulation data; most tabular work uses data frames instead.
Categorical data stored as integers with a set of levels, which controls ordering in tables, models and plots. Converting a factor of numbers with as.numeric() returns level codes, not the values.
The central structure for tabular data: a list of equal-length columns, each its own type. Subset with df[rows, cols], df$col, or dplyr verbs.
The tidyverse's data frame: prints only what fits the screen, never converts strings or changes column names, and warns on partial $ matching. Drop-in compatible with most base functions.
The data.table class extends data frames with the compact DT[i, j, by] syntax and in-place updates by reference, making it one of the fastest tools for large tables in any language.
Functions are ordinary objects created with function(x) { } or the shorthand \(x). They return the last evaluated expression, take arguments lazily and look up variables lexically — the keys to understanding most R behaviour.
Arguments match by exact name, partial name, then position; defaults can refer to other arguments because they are evaluated lazily. ... passes extra arguments on to other functions.
R looks up a name in the function's own environment, then where the function was defined, up to the global environment and attached packages. <<- assigns to an enclosing scope — useful in closures, risky elsewhere.
A function calling itself on a smaller problem, like walking nested lists or trees. R has no tail-call optimisation and a limited stack, so deep recursion should become a loop.
lapply() returns a list, sapply() simplifies when it can, vapply() enforces an output type, apply() works over matrix margins and mapply() iterates in parallel. Prefer vapply() in code that must be predictable.
R signals errors, warnings and messages as conditions. Raise them with stop(), warning() and message(); handle them with tryCatch() or withCallingHandlers(), and use try() when a failure should just return an error object.
Call traceback() after an error, insert browser() to pause inside a function, use debug()/debugonce() to step through, or set options(error = recover). RStudio breakpoints wrap the same tools.
The tidyverse is a family of packages sharing one design: data frames in, data frames out, verbs that read like sentences and tidy data with one variable per column. Most modern R data work is built on it.
library(tidyverse) attaches the core packages at once. Learn the shared conventions — tibbles, the pipe, tidy evaluation with bare column names — and every package feels familiar.
The data-manipulation grammar: filter(), select(), mutate(), arrange(), summarise() and group_by(), plus joins. Backends like dbplyr translate the same code to SQL.
Tools for getting data into tidy shape: pivot_longer(), pivot_wider(), separate_wider_delim(), unnest() and helpers for missing values such as drop_na() and fill().
Fast, consistent readers for delimited files: read_csv() guesses column types and reports problems; pin types with col_types for repeatable imports.
Functional programming tools: map() and its typed variants, map2(), pmap(), walk() for side effects, and safely()/possibly() to keep iterating when one element fails.
The package that defines the tibble class, with tibble() and row-wise tribble() constructors and as_tibble() for converting existing data frames.
Consistent str_* functions for detecting, extracting, replacing, splitting and padding strings, all taking the string first and a regular expression second.
Helpers for factors: reorder levels by another variable (fct_reorder()), by frequency (fct_infreq()), lump rare levels (fct_lump_n()) and rename them (fct_recode()).
Parsing and arithmetic for dates and times: ymd(), dmy_hms(), floor_date(), time zones with with_tz(), and periods versus durations for calendar-aware maths.
Getting data into R reliably is the first half of every project. Pick a reader suited to the format, set column types explicitly and check the parsing problems report before trusting the result.
readr::read_csv() for tidy imports, data.table::fread() for very large files, base read.csv() when you want no dependencies. Watch delimiters, decimal marks and encodings from other locales.
readxl::read_excel() reads .xls and .xlsx without Excel installed, with sheet and range arguments for messy workbooks; writexl or openxlsx2 write them.
readLines() and readr::read_lines() return one string per line; read_fwf() handles fixed-width files. Set the encoding when text comes from older Windows systems.
jsonlite::fromJSON() turns JSON into vectors, lists and data frames, simplifying where it can; deeply nested responses are easier with tidyr::unnest_wider() and unnest_longer().
httr2 builds requests with request() |> req_url_query() |> req_perform(), and handles auth, retries, rate limits and pagination. Parse the body with resp_body_json().
rvest reads HTML and extracts elements with CSS selectors via html_elements(), html_text2() and html_table(). Respect robots.txt and terms of use, and use polite to throttle.
Raw data arrives with wrong types, messy strings, gaps and extreme values. Cleaning is about making each of those explicit decisions, recorded in code, so the analysis can be rerun and audited.
Convert columns with mutate(across(cols, as.numeric)) or readr's parse_number(), which strips currency symbols and thousands separators. Count new NAs after every conversion.
Turn text into Date or POSIXct with lubridate's ymd()/dmy() family or base as.Date(x, format = "%d/%m/%Y"). Always state the time zone for datetimes.
Convert labels to factors with explicit levels, recode inconsistent spellings, and create dummy variables with model.matrix() or recipes' step_dummy() for modelling.
R's equivalents are trimws() or str_trim()/str_squish() to strip whitespace, gsub() or str_replace_all() to replace, and strsplit() or str_split() to split.
In R, is.na() tests for missing values (NA), while is.null() tests for the absence of an object. NA propagates through arithmetic, so many functions need na.rm = TRUE.
Dropping rows with drop_na() is simple but biased if data is not missing at random; imputing with a median, model or the mice package keeps rows but invents values. Document which you chose and why.
tidyr::fill(df, col, .direction = "down") carries the last known value forward — right for sorted sensor readings or spreadsheet group headers, wrong for independent observations.
Flag values below Q1 − 1.5×IQR or above Q3 + 1.5×IQR, the rule boxplots use. Robust to skew because quartiles are not dragged by the outliers themselves.
Standardise with scale() and flag values beyond about ±3 standard deviations. Assumes rough normality, and extreme points inflate the very standard deviation used to find them.
Histograms, boxplots and scatter plots reveal impossible values, data-entry errors and clusters that rules miss. Look before deciding whether an outlier is an error or the interesting part.
Turning clean data into the shape an analysis needs: subsetting, deriving columns, grouping, joining and reshaping. dplyr and tidyr cover it with readable verbs; data.table does the same with more speed and terser syntax.
filter() keeps rows matching conditions, select() picks columns with helpers like starts_with(), and arrange(desc(x)) sorts. slice_max() gets the top rows per group.
mutate() adds or modifies columns using other columns; across() applies one function to many columns; case_when() handles multi-branch logic.
group_by() then summarise() collapses each group to one row; the .by argument does a one-off grouping without leaving the result grouped. count() is a shortcut for frequency tables.
Functions that return one value per row but look at neighbours or the group: lag(), lead(), row_number(), min_rank() and cumulative cumsum(). Combine with group_by() and arrange() for per-group running totals.
left_join(), inner_join(), full_join(), plus filtering joins semi_join() and anti_join(). Use join_by() for explicit keys and the relationship argument to catch unexpected many-to-many matches.
pivot_longer() turns wide columns into key–value rows — what ggplot2 and most models want — and pivot_wider() reverses it for presentation tables.
purrr::map() applies a function to each element and returns a list; map_dbl(), map_chr() and friends return typed vectors. Combined with list-columns they make per-group models tidy.
In DT[i, j, by], i filters, j selects or computes and by groups; := adds columns by reference without copying. dtplyr lets you write dplyr verbs that run on data.table.
Text and time are where real-world data is messiest. Learn stringr and regular expressions for text, and lubridate with base date classes for time, including the time-zone traps.
Combine with paste0() or str_c(), interpolate with glue(), measure with str_length(), slice with str_sub() and change case with str_to_lower(). Use sprintf() or format() for number formatting.
Patterns for matching text, used by grepl(), sub(), str_detect() and str_extract(). Backslashes must be doubled in R strings ("\\d+"), or use raw strings r"(\d+)".
Date stores days, POSIXct stores seconds since 1970 with a time zone. Use lubridate for parsing, rounding and arithmetic; difftime and periods handle durations.
An iterative loop of asking questions, summarising and plotting before any formal modelling. The goal is to understand variation within variables and covariation between them, and to catch data problems early.
summary(), mean(), median(), sd(), quantile() and table() give quick overviews; skimr::skim() summarises a whole data frame with missing counts and mini histograms.
Look at shape, centre, spread and skew with histograms, density plots and Q–Q plots (qqnorm()). Try several bin widths — one histogram can hide or invent structure.
Scatter plots and correlations for two numeric variables, boxplots for numeric by category, and contingency tables for two categoricals. Always plot before computing a correlation.
The built-in graphics system: plot(), hist(), boxplot() and barplot() draw quickly with no packages, and lines(), points() and legend() add to an existing plot. Great for quick checks; ggplot2 scales better to complex, layered charts.
The most widely used R plotting package, built on a layered grammar: you map variables to aesthetics, choose geometric layers and adjust scales, facets and themes. One consistent system covers quick exploration and publication graphics.
Every plot is data plus aesthetic mappings, geoms, stats, scales, coordinates and facets, combined with +. Thinking in these parts makes new chart types a matter of swapping one component.
aes(x, y, colour, size, shape) links columns to visual properties; settings outside aes() apply constants. Putting a constant inside aes() creates a confusing legend.
geom_point(), geom_line(), geom_col() and geom_bar(), geom_histogram(), geom_boxplot() and geom_smooth() cover most needs. geom_bar() counts rows, geom_col() uses the values given.
When points pile up, use transparency (alpha), jitter, smaller points, 2D bins (geom_bin_2d(), geom_hex()) or density contours to show where data is dense.
facet_wrap() and facet_grid() split one plot into small multiples by category. Themes like theme_minimal() plus theme() tweaks control everything non-data.
Label axes with units via labs(), use colour-blind-safe palettes such as viridis, order categories meaningfully with forcats, and save at the right size with ggsave().
Interactive dashboards let others explore results without running R. Shiny builds full web apps in R; Quarto dashboards cover simpler static or lightly interactive cases; BI tools are an option when the organisation already uses them.
A web framework where a UI definition and a reactive server function update outputs automatically when inputs change. Deploy to Posit Connect, shinyapps.io or a Docker container.
Commercial BI tools that can run R scripts for custom visuals or calculations. Useful to fit into an existing BI stack, but packages and versions are limited by the host.
HTML widgets add hover, zoom and selection to charts in Quarto documents, Shiny apps and the RStudio viewer. Interactivity helps exploration but rarely replaces a clear static chart in a report.
plot_ly() builds interactive charts directly, and ggplotly() converts most ggplot2 plots with one call. Output is a self-contained HTML widget.
Statistics is R's home ground: tests, models and distributions are built in, and model objects work with summary(), predict(), anova() and plot(). Understand the assumptions behind each method before reading its p-values.
The base package loaded in every session with lm(), glm(), t.test(), cor(), distributions, aov() and time-series tools. Most other modelling packages follow its formula interface.
Pipe-friendly wrappers around common tests (t_test(), anova_test(), wilcox_test()) that return tidy data frames with effect sizes and adjusted p-values, ready for plotting.
Centre (mean, median), spread (sd, IQR, range) and shape (skewness) summarise a variable; grouped summaries with dplyr compare them across categories.
Each built-in distribution comes as a quartet of prefixed functions — dnorm() gives the density, pnorm() the CDF, qnorm() the inverse CDF and rnorm() random draws — and the same prefixes apply to binom, t, pois, exp and the rest.
sample() draws with or without replacement and slice_sample() samples rows; call set.seed() first for reproducibility. Bootstrapping resamples data to estimate uncertainty.
cor() computes Pearson, Spearman or Kendall coefficients and cor.test() adds a test. Correlation captures only monotonic or linear association and says nothing about causation.
t.test(), wilcox.test(), chisq.test() and aov() test differences between groups. Report effect sizes and confidence intervals alongside p-values, and correct for multiple comparisons.
lm(y ~ x1 + x2, data) fits ordinary least squares; summary() shows coefficients and R², and plot(model) draws diagnostics for checking residual assumptions.
Predictive modelling in R centres on tidymodels, which wraps many algorithms behind one interface and enforces good practice: split data, preprocess inside resampling, tune and evaluate on held-out data.
A set of packages: rsample for splits, recipes for preprocessing, parsnip for model specs, workflows to bundle them, tune for hyperparameters and yardstick for metrics.
Models a binary outcome with glm(y ~ ., family = binomial). Coefficients are log-odds; use predict(type = "response") for probabilities and pick the classification threshold deliberately.
Data indexed by time, with trend, seasonality and autocorrelation. The tidyverts packages (tsibble, feasts, fable) handle decomposition, ARIMA and exponential smoothing forecasts.
Text analysis in R turns documents into tokens, counts and matrices for sentiment analysis, topic modelling and classification. Two main styles exist: tidy one-token-per-row tables and document-feature matrices.
unnest_tokens() turns text into one token per row so dplyr and ggplot2 work on words directly; includes stop words, sentiment lexicons and tf-idf with bind_tf_idf().
A fast framework built around corpora, tokens and document-feature matrices, with keyword-in-context, collocations and dictionary analysis. Suited to large corpora and quantitative text research.
Studying relationships as graphs of nodes and edges: who is central, which communities exist, how things spread. R offers mature graph algorithms plus tidy interfaces and ggraph for plotting.
The core graph library (C underneath) for creating graphs, computing centrality, shortest paths, components and community detection such as cluster_louvain().
A tidy layer over igraph: treat nodes and edges as two tables, activate() one, and use dplyr verbs plus centrality and grouping functions. Pairs with ggraph for plotting.
R handles vector data (points, lines, polygons) and raster data (grids) with modern packages built on GDAL, GEOS and PROJ. Coordinate reference systems are the first thing to get right.
Simple Features for vector data: spatial objects are data frames with a geometry column, so dplyr works on them. st_read(), st_transform(), st_join() and st_buffer() are daily tools.
Fast raster (and vector) processing — elevation, satellite imagery, climate grids — with rast(), crop(), extract() and map algebra. Replaces the older raster package.
Thematic maps with a layered syntax similar to ggplot2, switching between static and interactive modes with tmap_mode().
Interactive web maps through the Leaflet JavaScript library: tiles, markers, polygons and popups, usable in Shiny and Quarto.
R works in memory and runs on one core by default. For larger data, use faster in-memory tools first (data.table, arrow, duckdb), then parallelism, and only then a cluster.
Base parallel provides mclapply() and socket clusters; the future framework (with furrr or future.apply) lets the same code run sequentially, on local cores or on remote workers.
A dplyr interface to Apache Spark: verbs are translated to Spark SQL and run on the cluster, with Spark MLlib models available too. Worth it only when data truly exceeds one machine.