Matrices
If you want to have multiple vectors combined together to create a two-dimensional space with rows and columns, we can use the rbind() and cbind() functions. This new object is called a matrix. rbind() stands for row bind and cbind() stands for column bind.
# no pec
matrix_r <- rbind(c(1, 2, 3, 4), c(5, 6, 7, 8), c(9, 10, 11, 12), c(13, 14, 15, 16))
matrix_r
matrix_c <- cbind(c(1, 2, 3, 4), c(5, 6, 7, 8), c(9, 10, 11, 12), c(13, 14, 15, 16))
matrix_c
When using rbind(), the vectors are stacked on top of each other and made into rows in the matrix.
When using cbind(), the vectors are stacked next to each other and made into columns in the matrix.
Both of these functions are useful and which one you will need to use will depend on your individual situation.
'[ , ]' notation
If you only want a subset of the data that is stored in a matrix, you can use bracket notation, '[ , ]'. Unlike vectors, matrices are two-dimensional and we need to specify the row and the column of the element(s) of interest.
matrix_c <- cbind(c(1, 2, 3, 4), c(5, 6, 7, 8), c(9, 10, 11, 12), c(13, 14, 15, 16))
matrix_c
matrix_c[3, 2] # This would give us the value 7.
You can subset more than one element of a matrix using a variety of methods.
matrix_c <- cbind(c(1, 2, 3, 4), c(5, 6, 7, 8), c(9, 10, 11, 12), c(13, 14, 15, 16))
# This will subset the matrix to only include the 2nd through 4th rows and the 1st column.
matrix_c[2:4, 1]
# This will subset the matrix to only include the 2nd row and the 1st and 3rd columns.
matrix_c[2, c(1, 3)]
If you want all of the elements in a row or column, leave its respective space empty in the brackets.
matrix_c <- cbind(c(1, 2, 3, 4), c(5, 6, 7, 8), c(9, 10, 11, 12), c(13, 14, 15, 16))
#This will show all of the rows in the 1st column
matrix_c[, 1]
#This will show all of the columns in the 2nd row
matrix_c[2, ]
#This will show the whole matrix
matrix_c[, ]