Skip to content
Volume R · The TensorCore.si Library

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.

Prologue

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.
Prologue

Set up and run your first program

Install R from CRAN and RStudio (or Positron) as your editor.

terminal
R --version
Rscript hello.R
hello.R
name <- "Ada"
cat("Hello, AI! Welcome to R,", name, "\n")
TipInstall packages with install.packages("tidyverse").
Chapter 1

Variables and vectors

Assign with <-. Almost everything is a vector, and operations apply to every element at once, so you rarely need loops.

vectors.R
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])
Chapter 2

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.

functions.R
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 precision
Chapter 3

Data frames

A data frame is a table: columns of equal length. It is the central data structure for analysis.

dataframes.R
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)
Chapter 4

The tidyverse with dplyr

dplyr verbs (filter, mutate, group_by, summarise) chained with the pipe |> make data manipulation read like a recipe.

dplyr.R
library(dplyr)
gpus |>
  mutate(vram_tb = vram / 1000) |>
  group_by(vendor) |>
  summarise(models = n(), max_vram = max(vram)) |>
  arrange(desc(max_vram))
Chapter 5

Charts with ggplot2

ggplot2 builds charts in layers: data, aesthetics and geometric shapes.

plot.R
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")
Part II · AI with R

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

tidymodelsA consistent framework for ML workflows.
torch for RPyTorch's engine with an R interface.
ellmerChat with LLMs, including tool calling.
xgboostFast gradient-boosted trees.

Gradient descent, vectorised

Because R works on whole vectors, the gradient fits in two lines with no inner loop.

gradient.R
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 agrees
Part III · Build an AI agent

Build 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.

Your goal→Model plans→Tool call→Your code runs the tool→Result back to model→Final answer
agent.R
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.

Run it locallyInstall Ollama, run 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.
Part IV · Your path

R learning roadmap

Tick items off as you go. Your progress is saved in this browser.

Beginner

Intermediate

Advanced

Part IV · Your path

Projects to build

Data reportAnalyse a CSV and publish a Quarto report.
Prediction modelTrain and evaluate a model with tidymodels.
Shiny chat appA web app that answers questions about your data.
Reference

R cheat sheet

TaskSyntax
Assignx <- 5
Vectorc(1, 2, 3)
Data framedata.frame(a = 1:3)
Filterdf |> filter(x > 1)
Summarisesummarise(m = mean(x))
Plotggplot(df, aes(x, y)) + geom_point()
Reference

Common mistakes

  • R indexes from 1, not 0.
  • Growing a vector inside a loop is slow; use vectorised code or preallocate.
  • NA spreads through calculations; use na.rm = TRUE where needed.
Reference

Where to go next

On TensorCore.si: Python volume, Julia volume.

Keyboard: [ previous language · ] next language · / search the library