Exercise

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)

Instructions

100 XP
  • 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.