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
v <- c(10, 20, 30, 40, 50)v[1] # 10 (R is 1-indexed!)v[c(1, 3, 5)] # 10 30 50 — multiple positionsv[-1] # 20 30 40 50 — exclude position 1v[v > 20] # 30 40 50 — boolean mask# Named vectornamed <- 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.
result <- list(name = "KCB",assets = 1500,rates = c(0.10, 0.12, 0.14))result$name # "KCB" — using $ for named accessresult[["assets"]] # 1500 — using double bracketsresult[[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
m <- matrix(1:12, nrow = 3, ncol = 4)m[1, ] # row 1 — a vectorm[, 1] # column 1m[1, 2] # element at row 1, col 2# Matrix arithmeticm * 2 # element-wisem %*% 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.