Matrices, the New Dimension
Intro to Matrices in R

Vectors were fun and all but we have to move on. We need a data structure that can hold even more data. We need matrices. A matrix is a data structure that holds elements in columns and rows. There are 3 main parts that make up a matrix.
matrix() # Function that sets up a matrix
my_matrix <- matrix(1:9, byrow = T, nrow = 3)
This matrix will have elements that span from 1 through 9, will be filled from left to right, and will have 3 rows so it looks like this:
my_matrix
[,1] [,2] [,3] #Number of Columns on top, Rows to the left
[,1] 1 2 3
[,2] 4 5 6
[,3] 7 8 9
Neat huh? It’s cleaner and more convenient looking by far. It’s kinda like you’re stacking vectors on top of each other. For actual data analysis you’ll have names not numbers so let’s fix that:
col_names_vector <- c("Class1", "Class2", "Class3")
row_names_vector <- c("Maria", "Christina", "Jake")colnames(my_matrix) <- col_names_vector
rownames(my_matrix) <- row_names_vector
my_matrix
Class1 Class2 Class3
Maria 1 2 3
Christina 4 5 6
Jake 7 8 9
Looking nicer with every step. Oh no! We forgot to add a column! What to do? Don’t worry, R has your back. Let’s use the cbind function.
new_vector <- c(10, 11, 12) #vector to be added to matrix
my_matrix <- cbind(my_matrix, new_vector)
my_matrix
Class1 Class2 Class3 new_vector #New column added
Maria 1 2 3 10
Christina 4 5 6 11
Jake 7 8 9 12
Problem solved. Adding a row? Same logic with the rbind function:
nrow_vector <- c(13, 14, 15, 16)
my_matrix <- rbind(my_matrix, nrow_vector)
my_matrix
Class1 Class2 Class3 new_vector
Maria 1 2 3 10
Christina 4 5 6 11
Jake 7 8 9 12
nrow_vector 13 14 15 16 #new row
Boom. That’s all for now. Next time we finish up matrices and perform an analysis with movie data. (Hint: it’s fantasy related.)
If you enjoyed and/or learned anything, hit the recommend button.