Matrices

In addition to the vector data structure, R has the matrix, data frame, list, and array data structures. Though we will be using all these types (except arrays) in this book, we only need to review the first two in this chapter.

A matrix in R, like in math, is a rectangular array of values (of one type) arranged in rows and columns, and can be manipulated as a whole. Operations on matrices are fundamental to data analysis.

One way of creating a matrix is to just supply a vector to the function matrix().

  > a.matrix <- matrix(c(1, 2, 3, 4, 5, 6))
  > a.matrix
       [,1]
  [1,]    1 
  [2,]    2 
  [3,]    3 
  [4,]    4 
  [5,]    5 
  [6,]    6

This produces a matrix with all the supplied values in a single column. We can make a similar matrix with two columns by supplying matrix() ...

Get R: Data Analysis and Visualization now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.