Matrices and Arrays
The garden now records harvests per week: plots down the side, weeks across the top. That is a grid of numbers, and when every cell holds the same type, R's matrix is the natural home. It comes with fast row and column totals, and one fill-order rule you must know.
The rule
A matrix is a vector with rows and columns, filled column by column.
# weeks 1 and 2 for plots A, B and C
m <- matrix(c(5, 3, 7, 7.5, 5, 8), nrow = 3)
rownames(m) <- c("A", "B", "C")
colnames(m) <- c("wk1", "wk2")Six values in 3 rows means 2 columns. R pours the values down the first column, then down the second:
| wk1 | wk2 | |
|---|---|---|
| A | 5 | 7.5 |
| B | 3 | 5 |
| C | 7 | 8 |
Add byrow = TRUE to fill across rows instead. Either way, a matrix is still one vector underneath, so it holds one type: put a single piece of text in and every cell becomes text.
Index with row, then column, separated by a comma. Leave a side blank to mean "all":
m[2, 1] # 3, plot B in week 1
m["B", ] # wk1 3, wk2 5: the whole row
m[, "wk2"] # A 7.5, B 5, C 8: the whole column
dim(m) # 3 2, rows then columns
rowSums(m) # A 12.5, B 8, C 15: each plot's total
colSums(m) # wk1 15, wk2 20.5: each week's totalA single row or column comes back as a plain vector. Add drop = FALSE, as in m[2, , drop = FALSE], to keep it as a one-row matrix. Other useful tools: t(m) swaps rows and columns, m * 2 doubles every cell, and %*% is true matrix multiplication.
An array is the same idea with more than two dimensions. Add seasons as a third dimension and you have a 3 × 2 × 4 block:
a <- array(0, dim = c(3, 2, 4)) # plots x weeks x seasons, all zeros
a[1, 2, 3] # plot 1, week 2, season 3The values fill the first dimension fastest, then the second, then the third: the same "columns first" rule, one level deeper.
The shortcut
To place values in a default matrix, fill column 1 from top to bottom, then column 2, and so on. The number of columns is the number of values divided by nrow.
Find the shape
6 values in 2 rows means 3 columns.
Drills
Answer fast — trust the rule.
What is matrix(1:6, nrow = 2)[1, 3]?
What is matrix(1:6, nrow = 2, byrow = TRUE)[1, 3]?
What is dim(matrix(1:12, ncol = 4))?
For the weekly harvest matrix m, what does colSums(m) return?
How many values does array(0, dim = c(3, 2, 4)) hold?
Remember
- A matrix is a vector with rows and columns, filled column by column.
- Shortcut: fill down column 1, then column 2; index as
[row, column], blank means all. - Trap: forgetting the fill order, and a single text value turning every cell into text.
