Chapter 4 Matrices

A matrix has 2 dimensions, rows and columns. The first number/vector in the []s represents rows and the second columns. Leaving either position blank will return all rows/columns:

mat <- matrix(data = 1:12,
       nrow = 4,
       ncol = 3)
mat
##      [,1] [,2] [,3]
## [1,]    1    5    9
## [2,]    2    6   10
## [3,]    3    7   11
## [4,]    4    8   12
# blank spaces technically not needed but improve code readability
mat[1, ] # first row
## [1] 1 5 9
mat[ , 1] # first column
## [1] 1 2 3 4
mat[c(2, 4), ] # rows 2 and 4, notice the c()
##      [,1] [,2] [,3]
## [1,]    2    6   10
## [2,]    4    8   12
mat[c(2, 4), 1:3] # elements 2 and 4 of columns 1-3
##      [,1] [,2] [,3]
## [1,]    2    6   10
## [2,]    4    8   12
colnames(mat) <- c("One","Two","Three")
rownames(mat) <- c("Un","Deux","Trois", "Quatre")

mat
##        One Two Three
## Un       1   5     9
## Deux     2   6    10
## Trois    3   7    11
## Quatre   4   8    12

 

To get the full matrix, we simply type its name. However, you can think of the same operation as asking for all rows and all columns of the matrix:

mat[ , ] # all rows, all columns
##        One Two Three
## Un       1   5     9
## Deux     2   6    10
## Trois    3   7    11
## Quatre   4   8    12