In addition to the vector data structure, R has the matrix, data frame, list, and array data structures. Though we will be using all these types (except arrays) in this book, we only need to review the first two in this chapter.
A matrix in R, like in math, is a rectangular array of values (of one type) arranged in rows and columns, and can be manipulated as a whole. Operations on matrices are fundamental to data analysis.
One way of creating a matrix is to just supply a vector to the function matrix().
This produces a matrix with all the supplied values in a single column. We can make a similar matrix with two columns by supplying matrix() with an optional argument, ncol, that specifies the number of columns.
Remember, matrix multiplication is only defined for matrices where the number of columns in the first matrix is equal to the number of rows in the second.
> a2.matrix
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> a3.matrix
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
> a2.matrix %*% a3.matrix
[,1] [,2] [,3]
[1,] 17 22 27
[2,] 22 29 36
[3,] 27 36 45
>
> # dim() tells us how many rows and columns
> # (respectively) there are in the given matrix
> dim(a2.matrix)
[1] 3 2
To index the element of a matrix at the second row and first column, you need to supply both of these numbers into the subscripting operator.
> a2.matrix[2,1]
[1] 2
Many useRs get confused and forget the order in which the indices must appear; remember—it's row first, then columns!
If you leave one of the spaces empty, R will assume you want that whole dimension:
> # returns the whole second column
> a2.matrix[,2]
[1] 4 5 6
> # returns the first row
> a2.matrix[1,]
[1] 1 4
And, as always, we can use vectors in our subscript operator:
> # give me element in column 2 at the first and third row
> a2.matrix[c(1, 3), 2]
[1] 4 6