R Matrices

R Matrices

A Matrix is a strict, 2-dimensional data structure consisting of rows and columns.

Just like vectors, every single element inside a matrix must share the exact same data type.


Creating a Matrix

To create a matrix, you use the matrix() function.

You pass in a vector of data, and then define the matrix dimensions using nrow and ncol.

By default, R fills the matrix column by column, not row by row!

Creating a Matrix:

# Creates a 2x3 matrix filled with numbers 1 through 6
my_matrix <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)
print(my_matrix)
# Output:
#      [,1] [,2] [,3]
# [1,]    1    3    5
# [2,]    2    4    6

Accessing Matrix Items

To access a specific item, you use square brackets with a comma: [row, column].

For example, my_matrix[2, 3] extracts the element in the 2nd row and 3rd column.

If you leave the row or column blank (e.g., my_matrix[2, ]), R will return that entire row or column!


Matrix Operations

Because matrices hold strictly homogeneous data, mathematical operations run blazing fast.

You can easily multiply, divide, or add entire matrices together using standard operators.

This makes matrices the ultimate choice for advanced algebra and machine learning algorithms!


Exercise 1 of 2

?

Which two arguments specifically dictate the dimensions of a new matrix?

Exercise 2 of 2

?

How would you extract the entire first row from a matrix named 'my_matrix'?