TExcelTAD
Home › R › R Matrices

R Matrices

A matrix is a two-dimensional table of values with rows and columns. Like a vector, all values in a matrix share one type. Create one with matrix(), giving the data and the number of rows or columns:

r · try it yourself
m <- matrix(1:6, nrow = 2)
m
dim(m)
nrow(m); ncol(m)
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
[1] 2 3
[1] 2
[1] 3

By default R fills a matrix column by column. Use byrow = TRUE to fill it row by row:

r · try it yourself
matrix(1:6, nrow = 2, byrow = TRUE)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

Naming rows and columns

r · try it yourself
sales <- matrix(c(12, 15, 9, 20, 18, 14), nrow = 2, byrow = TRUE,
                dimnames = list(c("North", "South"), c("Jan", "Feb", "Mar")))
sales
sales["South", "Feb"]
      Jan Feb Mar
North  12  15   9
South  20  18  14
[1] 18

Accessing elements

Use [row, column]. Leave one side empty to take a whole row or column:

r · try it yourself
sales <- matrix(c(12, 15, 9, 20, 18, 14), nrow = 2, byrow = TRUE,
                dimnames = list(c("North", "South"), c("Jan", "Feb", "Mar")))
sales[1, ]          # first row
sales[, "Mar"]      # one column
sales[, 2:3]        # columns 2 and 3
sales[sales > 14]   # all values over 14
Jan Feb Mar
 12  15   9
North South
    9    14
      Feb Mar
North  15   9
South  18  14
[1] 20 15 18

Selecting a single row or column drops the result to a plain vector. Add drop = FALSE to keep it a matrix.

Adding rows and columns

rbind() binds rows; cbind() binds columns:

r · try it yourself
m <- matrix(1:4, nrow = 2, dimnames = list(NULL, c("a", "b")))
rbind(m, c(10, 20))
cbind(m, total = rowSums(m))
      a  b
[1,]  1  3
[2,]  2  4
[3,] 10 20
     a b total
[1,] 1 3     4
[2,] 2 4     6

Row and column summaries

r · try it yourself
sales <- matrix(c(12, 15, 9, 20, 18, 14), nrow = 2, byrow = TRUE,
                dimnames = list(c("North", "South"), c("Jan", "Feb", "Mar")))
rowSums(sales)
colMeans(sales)
apply(sales, 1, max)   # 1 = rows, 2 = columns
North South
   36    52
 Jan  Feb  Mar
16.0 16.5 11.5
North South
   15    20

Matrix arithmetic

Ordinary operators work element by element. True matrix multiplication uses %*%, t() transposes and solve() inverts a square matrix or solves a linear system:

r · try it yourself
A <- matrix(c(2, 1, 1, 3), nrow = 2)
B <- matrix(c(1, 0, 4, 2), nrow = 2)
A * B        # element-wise
A %*% B      # matrix product
t(B)
solve(A, c(5, 10))   # solve A %*% x = c(5, 10)
     [,1] [,2]
[1,]    2    4
[2,]    0    6
     [,1] [,2]
[1,]    2   10
[2,]    1   10
     [,1] [,2]
[1,]    1    0
[2,]    4    2
[1] 1 3

Test yourself

How does matrix(1:4, nrow = 2) fill its values?

  1. Row by row
  2. Column by column
  3. Randomly
  4. Diagonally

What does m[2, ] select?

  1. The second column
  2. The second row
  3. The element at 2,2
  4. The second element

Which operator performs matrix multiplication?

  1. *
  2. %*%
  3. %x%
  4. ^