Get Started

Create a matrix!

Matrices are similar to vectors, except they are in 2 dimensions! Let's create a 2x2 matrix "by hand" using matrix().

matrix(data = c(2, 3, 4, 5), nrow = 2, ncol = 2)

     [,1] [,2]
[1,]    2    4
[2,]    3    5

Notice that the actual data for the matrix is passed in as a vector using c(), and is then converted to a matrix by specifying the number of rows and columns (also known as the dimensions).

Because the matrix is just created from a vector, the following is equivalent to the above code.

my_vector <- c(2, 3, 4, 5)

matrix(data = my_vector, nrow = 2, ncol = 2)

This is a part of the course

“Introduction to R for Finance”

View Course

Exercise instructions

  • my_vector has been defined for you.
  • Replace the ___ to create a 3x3 matrix from my_vector.
  • Print my_matrix.
  • By default, matrices fill down each row. Run the code in the last example and note how the matrix fills across by using byrow = TRUE. Compare this to the example given above.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# A vector of 9 numbers
my_vector <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)

# 3x3 matrix
my_matrix <- matrix(data = ___, nrow = ___, ncol = ___)

# Print my_matrix


# Filling across using byrow = TRUE
matrix(data = c(2, 3, 4, 5), nrow = 2, ncol = 2, byrow = TRUE)
Edit and Run Code