Matrices

Learning Outcomes

By the end of this tutorial, you will be able to:

  • Describe the characteristics of an R matrix.
  • Explain the relationship between matrices and vectors.
  • Create new matrices in R.
  • Perform element-wise operations on matrices.
  • Select and modify the elements of a matrix.
  • Explain how recycling works with matrix operations.

In R, matrices are a fundamental data structure used to represent two-dimensional collections of homogeneously typed values. Just like vectors, all elements in a matrix must have the same type: one of the six atomic modes. You can think of R matrices as generalizations of R vectors. Matrices are just vectors with a dimension attribute that tells R to interpret matrices as two-dimensional objects with rows and columns (while vectors don’t have dimensions).

That last point is worth sitting with for a moment: everything you already know about vectors—homogeneous data types, element-wise operations, recycling to resolve length differences—carries over to matrices, almost unchanged. The main new idea in this tutorial is how R keeps track of rows and columns on top of the familiar vector foundation.

Back to top