R
Statistics and data science, built in.
R is a language made for statistics, data analysis and visualisation. It is used across research, biostatistics and finance, and its tidyverse and ggplot2 packages make exploring data fast and beautiful.
Why learn R?
R has thousands of statistical methods ready to use and some of the best plotting tools anywhere, which is why statisticians and scientists love it.
- Statistics first: models, tests and distributions are built in.
- Visualisation: ggplot2 makes publication-quality charts.
- AI and ML: tidymodels, torch for R and ellmer connect R to modern ML and LLMs.
Set up and run your first program
Install R from CRAN and RStudio (or Positron) as your editor.
R --version
Rscript hello.Rname <- "Ada"
cat("Hello, AI! Welcome to R,", name, "\n")install.packages("tidyverse").Variables and vectors
Assign with <-. Almost everything is a vector, and operations apply to every element at once, so you rarely need loops.
layers <- 32
lr <- 3e-4
vram <- c(H100 = 80, H200 = 141, B200 = 180)
vram * 1.0e9 # every element at once
mean(vram)
names(vram[vram > 100])Control flow and functions
if, for and while exist, but vectorised functions are usually faster. Functions are created with function() and return their last value.
params <- function(layers, width = 4096) 12 * layers * width^2
for (epoch in 1:3) cat("epoch", epoch, "\n")
bits <- 8
label <- if (bits <= 8) "low precision" else "high precision"
format(params(32), big.mark = ",")
sapply(c(16, 8, 4), function(b) 8e9 * b / 8 / 1e9) # GB per precisionData frames
A data frame is a table: columns of equal length. It is the central data structure for analysis.
gpus <- data.frame(
name = c("H100", "H200", "MI355X", "RTX 5090"),
vendor = c("NVIDIA", "NVIDIA", "AMD", "NVIDIA"),
vram = c(80, 141, 288, 32)
)
gpus[gpus$vram >= 80, ]
summary(gpus$vram)The tidyverse with dplyr
dplyr verbs (filter, mutate, group_by, summarise) chained with the pipe |> make data manipulation read like a recipe.
library(dplyr)
gpus |>
mutate(vram_tb = vram / 1000) |>
group_by(vendor) |>
summarise(models = n(), max_vram = max(vram)) |>
arrange(desc(max_vram))Charts with ggplot2
ggplot2 builds charts in layers: data, aesthetics and geometric shapes.
library(ggplot2)
ggplot(gpus, aes(x = reorder(name, vram), y = vram, fill = vendor)) +
geom_col() +
coord_flip() +
labs(x = NULL, y = "Memory (GB)", title = "AI accelerator memory")AI with R
R covers classic machine learning (tidymodels, caret), deep learning through torch for R, and LLM access through packages like ellmer. It is especially strong for evaluating models statistically.
The essential libraries
Gradient descent, vectorised
Because R works on whole vectors, the gradient fits in two lines with no inner loop.
set.seed(0)
x <- seq(-1, 1, length.out = 100)
y <- 3 * x + 0.5 + rnorm(100, sd = 0.1)
w <- 0; b <- 0; lr <- 0.1
for (step in 1:500) {
err <- (w * x + b) - y
w <- w - lr * mean(2 * err * x)
b <- b - lr * mean(2 * err)
}
round(c(w = w, b = b), 2)
coef(lm(y ~ x)) # R's built-in linear model agreesBuild an AI agent in R
The ellmer package handles chat, streaming and tool calling. Define an R function as a tool, register it, and the model can call it.
library(ellmer)
get_weather <- function(city) paste0("It is 24°C and sunny in ", city, ".")
chat <- chat_ollama(model = "llama3.1")
chat$register_tool(tool(
get_weather,
"Get the current weather for a city",
arguments = list(city = type_string("City name"))
))
chat$chat("Should I take an umbrella in Lahore today?")The tool() signature has changed between ellmer versions; check ?tool for the version you install.
ollama pull llama3.1, and keep it running. The code talks to its OpenAI-compatible API at http://localhost:11434/v1, so the same program also works with vLLM, llama.cpp server or a cloud API by changing the URL, model name and adding an API key.R learning roadmap
Tick items off as you go. Your progress is saved in this browser.
Beginner
Intermediate
Advanced
Projects to build
R cheat sheet
| Task | Syntax |
|---|---|
| Assign | x <- 5 |
| Vector | c(1, 2, 3) |
| Data frame | data.frame(a = 1:3) |
| Filter | df |> filter(x > 1) |
| Summarise | summarise(m = mean(x)) |
| Plot | ggplot(df, aes(x, y)) + geom_point() |
Common mistakes
- R indexes from 1, not 0.
- Growing a vector inside a loop is slow; use vectorised code or preallocate.
NAspreads through calculations; usena.rm = TRUEwhere needed.
Where to go next
- R for Data Science — free book
- tidymodels — ML in R
- ellmer — LLMs in R
On TensorCore.si: Python volume, Julia volume.
Keyboard: [ previous language · ] next language · / search the library