Skip to content
Module 03 of 1250 min readBeginner

Vectors, lists, and matrices

Subsetting with [], [[]], and $; named vs unnamed; matrix arithmetic.

25%

Listen along

Read “Vectors, lists, and matrices” aloud

Plays in your browser using on-device text-to-speech — nothing leaves the page.

Learning objectives

By the end of this module, you should be able to:

  • 01Subset vectors with positive indices, negative indices, and boolean masks
  • 02Recognise that R is 1-indexed (not 0-indexed like Python or C)
  • 03Distinguish [ from [[ when extracting from lists
  • 04Perform matrix arithmetic, including %*% for matrix multiplication and solve() for inversion

Vectors, lists, and matrices are the three building blocks of R data structures. Get the subsetting rules right and the rest of the language follows.

Vectors — homogeneous, 1D

r
v <- c(10, 20, 30, 40, 50)
v[1] # 10 (R is 1-indexed!)
v[c(1, 3, 5)] # 10 30 50 — multiple positions
v[-1] # 20 30 40 50 — exclude position 1
v[v > 20] # 30 40 50 — boolean mask
# Named vector
named <- c(KCB = 1500, Equity = 1700, Coop = 600)
named["Equity"] # 1700

R is 1-indexed

v[1] is the first element, not the second. Coming from Python or any C-family language, this catches you for a week then fades. R is closer to math notation here than to programming convention.

Lists — heterogeneous, 1D

Lists hold arbitrary objects of different types. Use them when you need to bundle a mix of values, vectors, and other lists.

r
result <- list(
name = "KCB",
assets = 1500,
rates = c(0.10, 0.12, 0.14)
)
result$name # "KCB" — using $ for named access
result[["assets"]] # 1500 — using double brackets
result[[3]] # the rates vector

[ vs [[

Single brackets [ return a list (or vector) of the selected elements. Double brackets [[ extract a single element. The classic example: result[1] is a list of length 1 containing the name; result[[1]] is the name itself.

Matrices — homogeneous, 2D

r
m <- matrix(1:12, nrow = 3, ncol = 4)
m[1, ] # row 1 — a vector
m[, 1] # column 1
m[1, 2] # element at row 1, col 2
# Matrix arithmetic
m * 2 # element-wise
m %*% t(m) # matrix multiplication (not *)
solve(m %*% t(m)) # matrix inverse

Exercise

Create a vector of c(0.07, 0.10, 0.12, 0.15, 0.08) and select all rates above 0.10.

Key takeaways

  • R is 1-indexed: v[1] is the first element — this catches every Python/C programmer for a week
  • Single brackets [ return a sublist (or subvector); double brackets [[ extract a single element
  • %*% is matrix multiplication; * is elementwise. Confusing them is a top-three R bug
  • Named vectors (c(KCB = 1500, Equity = 1700)) combine vector behaviour with key-value lookup

Further reading

  1. 01
  2. 02
  3. 03

    Hands-On Programming with R

    Garrett Grolemund · O'Reilly · 2014

Loading progress…
LeadAfrikPublic Economics Hub