Language lab · Optional: statistics
📊 R
Concept → trace → write code → run tests → explain why → improve → mini-project. Start in the browser if you like; set up your own computer when you are ready.
📖 Topics with real code (13)
Every verified output below was produced by running the code with R version 4.4.1 (2024-06-14) -- "Race for Your Life" on 6 Nov 2026. Open a topic to edit the code and run it right here in your browser.
🌱 Beginner (5)
Vectors and data types
R works on vectors: even one number is a vector of length 1. Types include numeric, integer (5L), character and logical. class() shows the type; as.numeric() converts.
age <- 15L
height <- 1.62
student <- TRUE
name <- "Asha"
cat(name, age, height, student, "\n")
cat(class(age), class(height), class(student), class(name), "\n")
marks <- c(72, 95, 64, 88)
cat(as.numeric("88") + 2, length(marks), marks * 2, "\n")
✅ Verified output
Asha 15 1.62 TRUE integer numeric logical character 90 4 144 190 128 176
Arithmetic and logic on vectors
Operators work element by element. %/% is integer division and %% the remainder. Comparisons give logical vectors used for filtering.
a <- 17; b <- 5 cat(a + b, a - b, a * b, a / b, a %/% b, a %% b, a^2, "\n") x <- c(3, 8, 1, 9, 4) cat(x > 4, "\n") cat(x[x > 4], sum(x > 4), "\n") cat(TRUE && FALSE, TRUE || FALSE, !TRUE, "\n")
✅ Verified output
22 12 85 3.4 3 2 289 FALSE TRUE FALSE TRUE FALSE 8 9 2 FALSE TRUE FALSE
Conditionals and ifelse
if/else for single values; ifelse() works on whole vectors at once, which is how R code usually avoids loops.
marks <- 78
grade <- if (marks >= 90) "A+" else if (marks >= 75) "A" else if (marks >= 35) "Pass" else "Fail"
cat("Grade:", grade, "\n")
all_marks <- c(92, 78, 30, 55)
print(ifelse(all_marks >= 35, "pass", "fail"))
switch("sat", sat = , sun = cat("Weekend\n"), cat("School day\n"))
✅ Verified output
Grade: A [1] "pass" "pass" "fail" "pass" Weekend
Loops and seq
for walks a vector; seq and seq_along make sequences. Prefer vector operations; loops are fine for small jobs.
for (i in 1:5) {
if (i == 3) next
cat("for", i, "\n")
}
n <- 10
while (n > 0) { if (n < 4) break; cat("while", n, "\n"); n <- n - 3 }
print(seq(0, 1, by = 0.25))
print(outer(1:3, 1:3))
✅ Verified output
for 1
for 2
for 4
for 5
while 10
while 7
while 4
[1] 0.00 0.25 0.50 0.75 1.00
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 4 6
[3,] 3 6 9
Functions
function() creates a function; the last value is returned. Arguments can have defaults and be named.
area <- function(length, width = 1) length * width stats <- function(x) c(min = min(x), max = max(x), mean = mean(x)) cat(area(5, 3), area(7), area(width = 2, length = 9), "\n") print(stats(c(4, 9, 2, 7)))
✅ Verified output
15 7 18 min max mean 2.0 9.0 5.5
🌿 Intermediate (4)
Data frames
A data frame is a table: columns of equal length. Select rows with conditions, add columns, and summarise.
df <- data.frame(name = c("Asha", "Ravi", "Meena", "Imran"), class = c(8, 9, 8, 9), marks = c(88, 95, 72, 64))
df$grade <- ifelse(df$marks >= 75, "A", "B")
print(df[df$marks > 70, ])
print(aggregate(marks ~ class, data = df, FUN = mean))
cat("rows:", nrow(df), "columns:", ncol(df), "\n")
✅ Verified output
name class marks grade 1 Asha 8 88 A 2 Ravi 9 95 A 3 Meena 8 72 B class marks 1 8 80.0 2 9 79.5 rows: 4 columns: 4
Descriptive statistics
mean, median, sd, quantile and summary describe data; table() counts categories.
set.seed(42) heights <- round(rnorm(200, mean = 160, sd = 8), 1) print(round(c(mean = mean(heights), median = median(heights), sd = sd(heights)), 2)) print(quantile(heights, c(0.1, 0.5, 0.9))) print(table(cut(heights, breaks = c(130, 150, 160, 170, 190))))
✅ Verified output
mean median sd
159.78 159.85 7.80
10% 50% 90%
149.57 159.85 170.31
(130,150] (150,160] (160,170] (170,190]
21 83 75 21
Lists and apply functions
A list holds mixed items. lapply/sapply apply a function to each element; split + sapply gives group summaries.
student <- list(name = "Asha", marks = c(88, 92, 79), passed = TRUE)
str(student)
print(sapply(list(a = 1:5, b = c(10, 20)), mean))
scores <- c(88, 95, 72, 64, 81); cls <- c("8A", "8B", "8A", "8B", "8A")
print(sapply(split(scores, cls), max))
✅ Verified output
List of 3 $ name : chr "Asha" $ marks : num [1:3] 88 92 79 $ passed: logi TRUE a b 3 15 8A 8B 88 95
Strings
paste, sprintf, toupper, gsub, strsplit and nchar handle text; grepl finds patterns.
t <- trimws(" GayaGnan learning ")
cat(toupper(t), "|", sub("learning", "labs", t), "|", nchar(t), "\n")
print(strsplit(t, " ")[[1]])
cat(sprintf("Total: %.2f for %d items", 49.5 * 3, 3L), "\n")
print(grepl("^G", c("Gaya", "Ravi", "Gnan")))
✅ Verified output
GAYAGNAN LEARNING | GayaGnan labs | 17 [1] "GayaGnan" "learning" Total: 148.50 for 3 items [1] TRUE FALSE TRUE
🌳 Advanced (4)
Linear regression
lm() fits a straight line y = a + b·x by least squares; coef() gives the intercept and slope, and R² measures fit.
study_hours <- c(1, 2, 3, 4, 5, 6, 7, 8)
marks <- c(52, 55, 61, 64, 70, 73, 79, 84)
fit <- lm(marks ~ study_hours)
print(round(coef(fit), 3))
cat("R squared:", round(summary(fit)$r.squared, 4), "\n")
cat("predicted marks for 9 hours:", round(predict(fit, data.frame(study_hours = 9)), 1), "\n")
✅ Verified output
(Intercept) study_hours
46.571 4.595
R squared: 0.9948
predicted marks for 9 hours: 87.9
Hypothesis testing
t.test compares the means of two groups; a small p-value suggests the difference is unlikely to be chance.
set.seed(7)
group_a <- rnorm(30, mean = 72, sd = 8)
group_b <- rnorm(30, mean = 78, sd = 8)
res <- t.test(group_a, group_b)
cat("means:", round(mean(group_a), 1), round(mean(group_b), 1), "\n")
cat("t =", round(res$statistic, 3), " p =", signif(res$p.value, 3), "\n")
cat(if (res$p.value < 0.05) "significant at 5 %\n" else "not significant\n")
✅ Verified output
means: 75.2 78.3 t = -1.55 p = 0.127 not significant
Matrices and linear algebra
matrix() builds matrices; %*% multiplies, t() transposes, solve() inverts or solves systems, eigen() finds eigenvalues.
A <- matrix(c(2, 1, 1, 3), nrow = 2) b <- c(5, 10) x <- solve(A, b) print(x) print(A %*% x) print(round(eigen(A)$values, 4))
✅ Verified output
[1] 1 3
[,1]
[1,] 5
[2,] 10
[1] 3.618 1.382
Probability and simulation
sample and runif simulate experiments; the law of large numbers makes the simulated probability approach the exact one.
set.seed(1)
rolls <- sample(1:6, 60000, replace = TRUE)
print(round(table(rolls) / length(rolls), 3))
two_dice <- sample(1:6, 1e5, TRUE) + sample(1:6, 1e5, TRUE)
cat("P(sum = 7) simulated:", mean(two_dice == 7), " exact:", round(6 / 36, 4), "\n")
✅ Verified output
rolls
1 2 3 4 5 6
0.166 0.164 0.165 0.170 0.168 0.167
P(sum = 7) simulated: 0.16736 exact: 0.1667
🛠️ Set up and verify
- Install
winget install RProject.R
brew install r
sudo apt install r-base
- Editor: Visual Studio Code with R (REditorSupport) or RStudio.
- Create
hello.Rcat('Hello, GayaGnan!\n') - Run it and check the version
Rscript hello.R R --version
- Health check: paste what your terminal printed.
Install one language at a time. These commands only install or print versions; nothing here deletes files. Versions change: check the official page and note the version you installed.
🧭 The 14-lab path
- 00 · Setup and verify — install the runtime and editor, run hello world, print the version, fix PATH
- 01 · Syntax and trace — follow each line and the value of every variable
- 02 · Logic — conditionals and decision trees
- 03 · Loops — trace tables and loop challenges
- 04 · Functions — break problems down and test each piece
- 05 · Data structures — lists, maps, stacks, queues and trees you can see
- 06 · Debugging — bug cases with a hint ladder
- 07 · Algorithms — search, sort and Big-O comparison
- 08 · Files and data — read and write fixture files
- 09 · API or database — talk to a mock API or a sandbox database
- 10 · Testing — write tests and read failing assertions
- 11 · Security — secure coding and dependency hygiene for this language
- 12 · Project — one portfolio mini-project
- 13 · Assessment — quiz, coding test, rubric and an explain-your-answer prompt
📚 Modules
- vectors
- data frames
- functions
- tidy data
- plots
- statistical summaries
- reproducible scripts
- tests
🏗️ Mini-projects
- Synthetic course-performance analysis
- Descriptive analytics report
Projects use synthetic data only.