9.5 Matrices
A matrix is a 2 dimensional vector.
All columns in a matrix must have:
- the same type (numeric, character or logical)
- the same length
9.5.1 Creating a matrix
- From vectors with the rbind function:
<- c(1, 44)
x <- c(0, 12)
y <- c(34, 4)
z # rbind: bind rows
<- rbind(x, y, z) b
- From vectors with the cbind function:
<- c(1, 0, 34)
i <- c(44, 12, 4)
j # cbind: bind columns
<- cbind(i, j) k
- From scratch with the matrix function:
# nrow: number of rows
# ncol: number of columns
<- matrix(c(1, 0, 34, 44, 12, 4),
pp nrow=3,
ncol=2)
9.5.2 Two-dimensional object
Vectors have one index per element (1-dimension).
Matrices have two indices (2-dimensions) per element, corresponding to its corresponding location: row and column number:
- Fetching elements of a matrix:
The “coordinates” of an element in a 2-dimensional object will be first the row (on the left of the comma), then the column (on the right of the comma):
9.5.3 Matrix manipulation
- Add 1 to all elements of a matrix
<- b + 1 b
- Multiply by 3 all elements of a matrix
<- b * 3 b
- Subtract 2 to each element of the first row of a matrix
1, ] <- b[1, ] - 2 b[
- Replace elements that comply a condition:
# Replace all elements that are greater than 3 with NA
> 3 ] <- NA b[ b
HANDS-ON
- Create a matrix, using the 2 following vectors vv1 and vv2 as columns:
<- c(43, 21, 54, 65, 25, 44)
vv1 <- c(0, 1, 1, 0, 1, 0) vv2
Save the matrix in the object mm1.
- Add 2 to each element of mm1.