Matrices and Arrays
A matrix is a vector with two dimensions. An array adds a dimension attribute of any supported length, allowing higher-dimensional structures; R uses column-major ordering.
Follow dimensions and indexing as values are arranged into rectangular structures.
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.