Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 39 ยท Data Types and Structures

Matrices and Arrays in R

Create and use R matrices and arrays. Learn matrix(), dim(), indexing rows and columns, cbind and rbind, element-wise versus matrix multiplication, and solve().

A matrix is a two-dimensional table of values, with rows and columns, in which every value has the same type. Matrices are the natural structure for numeric grids: distances between cities, pixel brightness, the coefficients of linear equations, a table of scores for several students on several tests. An array extends the idea to three or more dimensions.

Under the hood, a matrix is just a vector with a dim attribute that says how to fold it into rows and columns. That means everything you learned in Vectors carries over.

Creating a matrix

R
m <- matrix(1:6, nrow = 2)
m
#>      [,1] [,2] [,3]
#> [1,]    1    3    5
#> [2,]    2    4    6

R fills the matrix column by column. If you want to fill row by row, set byrow = TRUE:

R
m <- matrix(1:6, nrow = 2, byrow = TRUE)
m
#>      [,1] [,2] [,3]
#> [1,]    1    2    3
#> [2,]    4    5    6

dim(m)
#> [1] 2 3

nrow(m)
#> [1] 2

ncol(m)
#> [1] 3

You give either nrow or ncol and R works out the other from the data length. If the data length does not fit, R recycles the values and warns you.

Row and column names

R
scores <- matrix(c(80, 90, 70, 85, 95, 60), nrow = 2, byrow = TRUE)
rownames(scores) <- c("Ana", "Ben")
colnames(scores) <- c("math", "art", "music")
scores
#>     math art music
#> Ana   80  90    70
#> Ben   85  95    60

Names are optional but make code and output far easier to read.

Indexing with [row, column]

Inside the brackets, the part before the comma selects rows and the part after selects columns. Leave a part empty to mean "all".

R
m[2, 3]        # row 2, column 3
#> [1] 6

m[1, ]         # all of row 1
#> [1] 1 2 3

m[, 2]         # all of column 2
#> [1] 2 5

m[, c(1, 3)]   # columns 1 and 3
#>      [,1] [,2]
#> [1,]    1    3
#> [2,]    4    6

With names you can write scores["Ben", "art"], which gives 95.

Notice that m[1, ] returned a plain vector, not a one-row matrix. R drops dimensions of length one by default. Add drop = FALSE to keep the matrix shape: m[1, , drop = FALSE].

Assignment works the same way: m[2, 3] <- 0 replaces one cell, and m[m > 4] <- 0 replaces every value matching a condition.

Building matrices from vectors

cbind() binds vectors as columns and rbind() binds them as rows:

R
cbind(a = 1:2, b = 3:4)
#>      a b
#> [1,] 1 3
#> [2,] 2 4

rbind(1:3, 4:6)
#>      [,1] [,2] [,3]
#> [1,]    1    2    3
#> [2,]    4    5    6

Arithmetic: element-wise versus matrix

Ordinary operators work cell by cell:

R
m * 2
#>      [,1] [,2] [,3]
#> [1,]    2    4    6
#> [2,]    8   10   12

Two matrices of the same shape can be added or multiplied element by element. True matrix multiplication (rows times columns) uses a different operator, %*%. The inner dimensions must match: an (r x n) matrix times an (n x c) matrix gives (r x c).

R
t(m)                 # transpose: swap rows and columns
#>      [,1] [,2]
#> [1,]    1    4
#> [2,]    2    5
#> [3,]    3    6

m %*% t(m)           # (2 x 3) times (3 x 2) gives (2 x 2)
#>      [,1] [,2]
#> [1,]   14   32
#> [2,]   32   77

The top-left value is 1x1 + 2x2 + 3x3 = 14. Confusing * with %*% is the most common matrix mistake. Check the shapes with dim() when you get an error like non-conformable arguments.

Summaries by row and column

R
rowSums(m)
#> [1]  6 15

colMeans(m)
#> [1] 2.5 3.5 4.5

apply(m, 1, sum)     # apply a function over rows (1) or columns (2)
#> [1]  6 15

apply(m, 2, sum)
#> [1] 5 7 9

apply() is the general tool; rowSums(), colSums(), rowMeans() and colMeans() are faster special cases. You will see more of this idea in The apply Family.

Linear algebra basics

R includes the standard tools:

R
A <- matrix(c(2, 1, 1, 3), nrow = 2)
A
#>      [,1] [,2]
#> [1,]    2    1
#> [2,]    1    3

det(A)
#> [1] 5

solve(A)             # the inverse
#>      [,1] [,2]
#> [1,]  0.6 -0.2
#> [2,] -0.2  0.4

solve(A, c(5, 10))   # solve A x = b
#> [1] 1 3

solve(A, b) finds the vector x that satisfies the equations 2x + y = 5 and x + 3y = 10. Also available: diag() for diagonal and identity matrices (diag(3)), and eigen() for eigenvalues.

Arrays

An array has any number of dimensions. A three-dimensional array is like a stack of matrices:

R
a <- array(1:24, dim = c(2, 3, 4))
dim(a)
#> [1] 2 3 4

a[1, 2, 3]       # row 1, column 2, layer 3
#> [1] 15

a[, , 1]         # the first layer, a 2 x 3 matrix
#>      [,1] [,2] [,3]
#> [1,]    1    3    5
#> [2,]    2    4    6

Arrays appear in image data (height, width, color channel) and in multi-way tables. Most everyday analysis uses matrices and, more often, data frames.

Matrix or data frame?

A matrix needs one type for all cells. If you try to mix numbers and text, everything becomes text. For tables with columns of different types, such as names, ages and dates, use a data frame instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. By default, matrix(1:6, nrow = 2) fills values in which order?

    R fills by column unless byrow = TRUE is given.
  2. 2. What does m[, 2] select?

    Before the comma are rows, after it columns; leaving the row part empty means all rows.
  3. 3. What is the difference between * and %*% for matrices?

    Use %*% for matrix products, which also requires matching inner dimensions.
  4. 4. What shape is a <- array(1:24, dim = c(2, 3, 4))?

    dim lists rows, columns, then layers, so it is 4 layers of 2 x 3.

Summary

  • A matrix is a 2-D table of one type; an array generalizes to more dimensions.
  • matrix() fills by column unless byrow = TRUE; cbind() and rbind() join vectors.
  • Index with [rows, columns]; empty means all; drop = FALSE keeps the matrix shape.
  • * is element-wise, %*% is matrix multiplication, t() transposes, solve() inverts or solves equations.
  • Use rowSums(), colMeans() and apply() for summaries.

Next: Lists