Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

R Documentation

The language of statistics — data analysis, statistical models and beautiful charts.

R is a language built for statistics and data analysis. It has vectors and data frames at its core, thousands of packages on CRAN for statistics, machine learning and bioinformatics, and the tidyverse (dplyr, ggplot2) for clean data wrangling and beautiful charts. Data scientists, researchers and analysts use it daily.

1. Introduction & Installation

  1. Install R from CRAN.
  2. Install RStudio Desktop (free IDE) from posit.co — or use VS Code with the R extension.
  3. Install packages from the console: install.packages("tidyverse"), then load them with library(tidyverse).
R --version
Rscript analysis.R        # run a script from the terminal
cat("Hello, Codify!\n")

Output:

Hello, Codify!

⚠️ Common error: Error in library(dplyr): there is no package called 'dplyr' — install it first with install.packages("dplyr").

2. Basic Syntax

  • Assignment uses <- (= also works). Comments start with #.
  • Typing a value prints it; scripts use print() or cat().
  • R is vectorised: operations apply to every element at once.
  • Indexing starts at 1.
name <- "Asha"
score <- 90
score <- score + 5
cat(name, "scored", score, "\n")
cat(sprintf("Next level at %d points\n", score + 10))
print(c(1, 2, 3) * 10)

Output:

Asha scored 95 
Next level at 105 points
[1] 10 20 30

[1] in printed output is the index of the first element shown on that line.

⚠️ Common error: Error: object 'Score' not found — R is case-sensitive (score ≠ Score).

3. Variables & Data Types

Type Example
numeric (double) 3.14, 42
integer 42L
character "text"
logical TRUE, FALSE, NA
factor categorical data with levels
vector, list, matrix, data frame data structures
x <- 42
y <- 42L
s <- "data"
flag <- TRUE
cat(class(x), class(y), class(s), class(flag), "\n")
cat(7 / 2, 7 %/% 2, 7 %% 2, 2^10, "\n")
cat(as.integer("15") + 1, as.numeric("2.5") * 2, as.character(99), "\n")
cat(is.na(NA), NA + 1, "\n")
size <- factor(c("S", "M", "S", "L"), levels = c("S", "M", "L"))
print(table(size))

Output:

numeric integer character logical 
3.5 3 1 1024 
16 5 99 
TRUE NA 
size
S M L 
2 1 1 

NA means "missing value" — most calculations with NA return NA unless you pass na.rm = TRUE.

⚠️ Common error: mean(c(1, NA, 3)) returns NA. Use mean(c(1, NA, 3), na.rm = TRUE).

4. Operators & Vectors

Arithmetic + - * / ^ %% (mod) %/% (integer division), comparison == != < > <= >=, logical & | ! (vectorised) and && || (single values), membership %in%, sequences :.

v <- c(5, 3, 8, 1, 9)
print(v * 2)
print(v > 4)
print(v[v > 4])
print(sum(v)); print(mean(v)); print(sort(v, decreasing = TRUE))
print(1:5)
print(seq(0, 1, by = 0.25))
print(rep("ha", 3))
print(c(2, 7) %in% v)
print(length(v)); print(v[2]); print(v[-1]); print(rev(v))

Output:

[1] 10  6 16  2 18
[1]  TRUE FALSE  TRUE FALSE  TRUE
[1] 5 8 9
[1] 26
[1] 5.2
[1] 9 8 5 3 1
[1] 1 2 3 4 5
[1] 0.00 0.25 0.50 0.75 1.00
[1] "ha" "ha" "ha"
[1] FALSE FALSE
[1] 5
[1] 3
[1] 3 8 1 9
[1] 9 1 8 3 5

v[-1] removes the first element (negative indices exclude).

5. Conditional Statements

marks <- 82
if (marks >= 90) {
  grade <- "A"
} else if (marks >= 75) {
  grade <- "B"
} else {
  grade <- "C"
}
cat("Grade", grade, "\n")

scores <- c(91, 66, 85, 40)
print(ifelse(scores >= 50, "pass", "fail"))     # vectorised if

day <- "sat"
type <- switch(day, sat = , sun = "weekend", "weekday")
print(type)

Output:

Grade B 
[1] "pass" "pass" "pass" "fail"
[1] "weekend"

⚠️ Common error: the condition has length > 1 — if needs a single TRUE/FALSE. Use ifelse() for vectors, or any()/all().

6. Loops & Apply Functions

for (i in 1:3) cat("i =", i, "\n")

n <- 1
while (n < 100) n <- n * 3
cat("n =", n, "\n")

for (fruit in c("apple", "mango")) cat(toupper(fruit), "")
cat("\n")

# idiomatic R: apply a function over elements instead of looping
print(sapply(1:5, function(x) x^2))
print(vapply(c("data", "science"), nchar, integer(1)))
nums <- list(a = 1:3, b = 4:6)
print(lapply(nums, sum))

Output:

i = 1 
i = 2 
i = 3 
n = 243 
APPLE MANGO 
[1]  1  4  9 16 25
   data science 
      4       7 
$a
[1] 6

$b
[1] 15

sapply/vapply return vectors, lapply returns a list, apply works on matrix rows/columns, and Map/mapply loop over several inputs.

7. Functions

add <- function(a, b = 10) {
  a + b                       # last expression is returned
}

stats <- function(x) {
  list(mean = mean(x), sd = round(sd(x), 2), range = range(x))
}

square <- \(x) x^2            # short lambda syntax (R 4.1+)

print(add(5))
print(add(2, b = 3))
s <- stats(c(91, 78, 85, 66, 92))
cat("mean", s$mean, "sd", s$sd, "range", s$range, "\n")
print(square(1:4))
print(Reduce(`+`, 1:5, accumulate = TRUE))

Output:

[1] 15
[1] 5
mean 82.4 sd 10.74 range 66 92 
[1]  1  4  9 16
[1]  1  3  6 10 15

8. Data Structures: Lists, Matrices & Data Frames

student <- list(name = "Neha", marks = c(85, 92, 78), active = TRUE)
cat(student$name, mean(student$marks), "\n")

m <- matrix(1:6, nrow = 2)
print(m)
print(dim(m)); print(t(m) %*% m)

df <- data.frame(
  name  = c("Asha", "Ravi", "Neha", "Kabir"),
  city  = c("Pune", "Delhi", "Pune", "Mumbai"),
  marks = c(91, 78, 85, 66)
)
print(nrow(df)); print(names(df))
print(df[df$marks > 80, c("name", "marks")])
df$grade <- ifelse(df$marks >= 85, "A", "B")
print(aggregate(marks ~ city, data = df, FUN = mean))
print(df[order(-df$marks), "name"])

Output:

Neha 85 
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
[1] 2 3
     [,1] [,2] [,3]
[1,]    5   11   17
[2,]   11   25   39
[3,]   17   39   61
[1] 4
[1] "name"  "city"  "marks"
  name marks
1 Asha    91
3 Neha    85
    city marks
1  Delhi    78
2 Mumbai    66
3   Pune    88
[1] "Asha"  "Neha"  "Ravi"  "Kabir"

Useful functions: head(), str(), summary(), read.csv()/write.csv(), merge(), table(), unique().

⚠️ Common error: forgetting the comma when filtering rows — df[df$marks > 80] selects columns. Write df[df$marks > 80, ].

9. Object-Oriented Programming

R has several OOP systems. S3 is the simplest and most common: an object is a list with a class attribute, and generic functions dispatch on it.

account <- function(owner, balance = 0) {
  structure(list(owner = owner, balance = balance), class = "account")
}

print.account <- function(x, ...) {               # method for the print() generic
  cat("Account of", x$owner, "with balance", x$balance, "\n")
}

deposit <- function(acc, amount) UseMethod("deposit")   # a new generic
deposit.account <- function(acc, amount) {
  stopifnot(amount > 0)
  acc$balance <- acc$balance + amount
  acc                                            # R objects are copied: return the new one
}

a <- account("Asha")
a <- deposit(a, 500)
print(a)
print(inherits(a, "account"))

Output:

Account of Asha with balance 500 
[1] TRUE

Other systems: S4 (formal classes with setClass, used in Bioconductor) and R6 (package R6: mutable objects with methods, similar to classes in other languages).

10. Advanced Concepts: tidyverse, Visualisation & Statistics

dplyr — readable data manipulation with the pipe |> (or %>%):

library(dplyr)

students <- tibble(
  name  = c("Asha", "Ravi", "Neha", "Kabir", "Isha"),
  city  = c("Pune", "Delhi", "Pune", "Mumbai", "Delhi"),
  marks = c(91, 78, 85, 66, 92)
)

students |>
  filter(marks >= 70) |>
  group_by(city) |>
  summarise(students = n(), avg = mean(marks)) |>
  arrange(desc(avg))
# A tibble: 2 × 3
  city  students   avg
  <chr>    <int> <dbl>
1 Pune         2    88
2 Delhi        2    85

Other verbs: select(), mutate(), rename(), left_join(), pivot_longer()/pivot_wider() (tidyr), count().

ggplot2 — the grammar of graphics:

library(ggplot2)
ggplot(students, aes(x = reorder(name, marks), y = marks, fill = city)) +
  geom_col() +
  coord_flip() +
  labs(title = "Marks by student", x = NULL, y = "Marks") +
  theme_minimal()
ggsave("marks.png", width = 6, height = 4)

Statistics built in:

hours <- c(2, 4, 6, 8, 10)
score <- c(50, 60, 70, 80, 90)
model <- lm(score ~ hours)           # linear regression
print(coef(model))
cat("correlation:", cor(hours, score), "\n")
cat("prediction for 7 hours:", predict(model, data.frame(hours = 7)), "\n")
(Intercept)       hours 
         40           5 
correlation: 1 
prediction for 7 hours: 75 

Also: t.test(), chisq.test(), summary(model), glm() (logistic regression), time series (ts, forecast), machine learning with tidymodels/caret, reports with R Markdown/Quarto, and dashboards with Shiny.

11. Examples with Output

Example 1 — Word frequency, top 3

text <- "the cat and the hat and the bat"
freq <- sort(table(strsplit(text, " ")[[1]]), decreasing = TRUE)
print(head(freq, 3))

the and bat 
  3   2   1 

Example 2 — Normalise a vector to 0–1

x <- c(10, 20, 15, 30)
print((x - min(x)) / (max(x) - min(x)))
[1] 0.00 0.50 0.25 1.00

Example 3 — Simulate 1000 dice rolls

set.seed(42)                         # reproducible random numbers
rolls <- sample(1:6, 1000, replace = TRUE)
cat("average roll:", round(mean(rolls), 2), "\n")
cat("sixes:", sum(rolls == 6) > 100, "\n")
average roll: 3.41 
sixes: TRUE 

12. Practice Problems

  1. Create a vector of 10 random marks (sample(40:100, 10)) and print the mean, median and how many are above 75.
  2. Write a function grade(marks) that returns A/B/C for a whole vector using ifelse or cut().
  3. Load a CSV with read.csv(), show str() and summary(), and handle missing values.
  4. With dplyr, find the top 3 cities by average marks from a students data frame.
  5. Plot a histogram and a boxplot of marks with ggplot2.
  6. Fit a linear regression of salary on experience and predict a new value.
  7. Write an S3 class rectangle with print and area methods.
  8. Build a small Shiny app with a slider that changes a plot.

13. Interview Questions

1. Vector vs list? A vector holds elements of one type; a list can hold elements of different types (including other lists).

2. What is a data frame? A table where each column is a vector of equal length (columns can have different types) — R's main structure for datasets.

3. What is NA vs NULL? NA is a missing value inside a vector; NULL represents "nothing" (an empty object, e.g. removing a list element).

4. What is vectorisation and why is it fast? Applying operations to whole vectors at once; the loops run in optimised C code rather than interpreted R.

5. apply, lapply, sapply differences? apply works on matrix margins, lapply returns a list, sapply simplifies the result to a vector/matrix when possible.

6. What is a factor? A categorical variable stored as integers with labelled levels — used in modelling and grouping.

7. What does the pipe operator do? x |> f(y) passes x as the first argument to f, letting you chain steps left to right.

8. S3 vs S4 vs R6? S3 is informal generic-function OOP; S4 adds formal class definitions and validation; R6 provides mutable reference objects with methods.

9. How do you handle missing data? Detect with is.na(), count with sum(is.na(x)), remove with na.omit(), or impute (mean/median/models); use na.rm = TRUE in summaries.

10. What is set.seed() for? Making random number generation reproducible so analyses give the same results every run.

14. Cheat Sheet & References

Basics

# assignment, printing, help
x <- 5; print(x); cat("x =", x, "\n"); sprintf("%.2f", pi)
class(x); str(x); is.na(x); as.numeric("3"); as.character(3)
?mean; help(package = "dplyr"); install.packages("ggplot2"); library(ggplot2)

Vectors

v <- c(1, 2, 3); 1:10; seq(0, 1, 0.1); rep(0, 5)
length(v); sum(v); mean(v); median(v); sd(v); max(v); range(v)
v[2]; v[-1]; v[v > 1]; which(v == 2); sort(v); rev(v); unique(v)
v %in% c(2, 3); paste("a", "b", sep = "-"); paste0("id", 1:3)

Data frames

df <- data.frame(a = 1:3, b = c("x", "y", "z"))
head(df); nrow(df); ncol(df); names(df); summary(df)
df$a; df[df$a > 1, ]; df[order(df$a), ]; df$c <- df$a * 2
read.csv("data.csv"); write.csv(df, "out.csv", row.names = FALSE)
aggregate(a ~ b, data = df, FUN = mean); merge(df1, df2, by = "id")

Control flow and functions

if (x > 0) { } else if (x == 0) { } else { }
ifelse(v > 1, "big", "small")
for (i in 1:5) { }; while (cond) { }
f <- function(a, b = 2) a + b; sq <- \(x) x^2
sapply(v, f); lapply(lst, f); Map(f, v1, v2)

dplyr and ggplot2

df |> filter(a > 1) |> select(a, b) |> mutate(c = a * 2) |> arrange(desc(c))
df |> group_by(b) |> summarise(n = n(), avg = mean(a))
left_join(x, y, by = "id"); count(df, b)
ggplot(df, aes(x = a, y = c)) + geom_point() + geom_smooth(method = "lm")

Statistics

cor(x, y); t.test(x, y); lm(y ~ x); summary(model); predict(model, newdata)
table(f); prop.table(table(f)); quantile(v); set.seed(1); sample(1:10, 3)

Official documentation