2.3 Matrices

Matrices are rectangular objects that we can think of as being made up of vectors.

We can make matrices by binding vectors that already exist.

cbind(a, e)
##      a   e      
## [1,] "1" "AAAAa"
## [2,] "2" "AAAAb"
## [3,] "3" "AAAAc"
## [4,] "4" "AAAAd"
## [5,] "5" "AAAAe"

Or we can make an empty one to fill.

matrix(0, nrow = 3, ncol = 4)
##      [,1] [,2] [,3] [,4]
## [1,]    0    0    0    0
## [2,]    0    0    0    0
## [3,]    0    0    0    0

Or we can make one from scratch.

mat <- matrix(seq(1, 12), ncol = 3, nrow = 4)

We can do all of the things we did with vectors to matrices, but now we have more than one column, and a second dimension in the form of “rows” that we can also use to these ends:

ncol(mat) # Number of columns
nrow(mat) # Number of rows
length(mat) # Total number of entries
mat[2, 3] # Value of row 2, column 3
str(mat)

See how number of rows and columns is defined in data structure? With rows and columns, we can assign column names and row names.

colnames(mat) <- c("first", "second", "third")
rownames(mat) <- c("This", "is", "a", "matrix")

# Take a look
mat
##        first second third
## This       1      5     9
## is         2      6    10
## a          3      7    11
## matrix     4      8    12

We can also do math on matrices just like vectors, because matrices are just vectors smooshed into two dimensions (it’s totally a word).

mat * 2
##        first second third
## This       2     10    18
## is         4     12    20
## a          6     14    22
## matrix     8     16    24

All the same operations we did on vectors above…one example.

More on matrices as we need them. We won’t use these a lot in this module, but R relies heavily on matrices to do linear algebra behind the scenes in the models that we will be working with.