What's a matrix?
In R, a matrix is a collection of elements of the same data type (numeric, character, or logical) arranged into a fixed number of rows and columns. Since you are only working with rows and columns, a matrix is called two-dimensional.
You can construct a matrix in R with the matrix()
function. Consider the following example:
matrix(1:9, byrow = TRUE, nrow = 3)
In the matrix()
function:
- The first argument is the collection of elements that R will arrange into the rows and columns of the matrix. Here, we use
1:9
which is a shortcut forc(1, 2, 3, 4, 5, 6, 7, 8, 9)
. - The argument
byrow
indicates that the matrix is filled by the rows. If we want the matrix to be filled by the columns, we just placebyrow = FALSE
. - The third argument
nrow
indicates that the matrix should have three rows.
This is a part of the course
“Introduction to R”
Exercise instructions
Construct a matrix with 3 rows containing the numbers 1 up to 9, filled row-wise.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Construct a matrix with 3 rows that contain the numbers 1 up to 9
This exercise is part of the course
Introduction to R
Master the basics of data analysis in R, including vectors, lists, and data frames, and practice R with real data sets.
In this chapter, you will learn how to work with matrices in R. By the end of the chapter, you will be able to create matrices and understand how to do basic computations with them. You will analyze the box office numbers of the Star Wars movies and learn how to use matrices in R. May the force be with you!
Exercise 1: What's a matrix?Exercise 2: Analyze matrices, you shallExercise 3: Naming a matrixExercise 4: Calculating the worldwide box officeExercise 5: Adding a column for the Worldwide box officeExercise 6: Adding a rowExercise 7: The total box office revenue for the entire sagaExercise 8: Selection of matrix elementsExercise 9: A little arithmetic with matricesExercise 10: A little arithmetic with matrices (2)What is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.