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”
Exercise instructions
my_vector
has been defined for you.- Replace the
___
to create a 3x3 matrix frommy_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)
This exercise is part of the course
Introduction to R for Finance
Learn essential data structures such as lists and data frames and apply that knowledge directly to financial examples.
In this chapter, you will learn all about vectors and matrices using historical stock prices for companies like Apple and IBM. You will then be able to feel confident creating, naming, manipulating, and selecting from vectors and matrices.
Exercise 1: What is a vector?Exercise 2: c()ombineExercise 3: Coerce itExercise 4: Vector names()Exercise 5: Visualize your vectorExercise 6: Vector manipulationExercise 7: Weighted average (1)Exercise 8: Weighted average (2)Exercise 9: Weighted average (3)Exercise 10: Vector subsettingExercise 11: Matrix - a 2D vectorExercise 12: Create a matrix!Exercise 13: Matrix <- bind vectorsExercise 14: Visualize your matrixExercise 15: cor()relationExercise 16: Matrix subsettingWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.