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:
x <- c(1, 44)
y <- c(0, 12)
z <- c(34, 4)
# rbind: bind rows
b <- rbind(x, y, z)
  • From vectors with the cbind function:
i <- c(1, 0, 34)
j <- c(44, 12, 4)
# cbind: bind columns
k <- cbind(i, j)
  • From scratch with the matrix function:
# nrow: number of rows
# ncol: number of columns
pp <- matrix(c(1, 0, 34, 44, 12, 4), 
    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):

rstudio logo

9.5.3 Matrix manipulation

  • Add 1 to all elements of a matrix
b <- b + 1
  • Multiply by 3 all elements of a matrix
b <- b * 3
  • Subtract 2 to each element of the first row of a matrix
b[1, ] <- b[1, ] - 2
  • Replace elements that comply a condition:
# Replace all elements that are greater than 3 with NA
b[ b > 3 ] <- NA

HANDS-ON

  1. Create a matrix, using the 2 following vectors vv1 and vv2 as columns:
vv1 <- c(43, 21, 54, 65, 25, 44)
vv2 <- c(0, 1, 1, 0, 1, 0)

Save the matrix in the object mm1.

  1. Add 2 to each element of mm1.