Make a matrix in R

A matrix is a 2D object with rows and columns that contains data all of the same kind, e.g. all numbers or all text. You can make a matrix in various ways:

  • The matrix() command – this splits a vector into rows and columns.
  • The rbind() command – this takes several items and joins them together as rows. You usually join several vectors but you can also use this to join an existing matrix to another matrix or vectors.
  • The cbind() command – this is similar to rbind() but operates over columns.

The matrix() command assumes that the vector of data will split “nicely” into rows and columns; if it doesn’t then you may have to add NA items at the end to make it factorise.

> dat <- 1:12
> dat
[1]  1  2  3  4  5  6  7  8  9 10 11 12

> matrix(dat, ncol = 3)
     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12

> matrix(dat, ncol = 3, byrow = TRUE)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
[4,]   10   11   12

The vector is split column-wise unless you specify that you want to fill row-wise using the byrow = TRUEparameter.

The rbind() and cbind() commands join items as rows or columns:

> d1 <- 1:4 ; d2 = 5:8 ; d3 = 9:12
> d1 ; d2 ; d3
[1] 1 2 3 4
[1] 5 6 7 8
[1]  9 10 11 12

> rbind(d1, d2, d3)
   [,1] [,2] [,3] [,4]
d1    1    2    3    4
d2    5    6    7    8
d3    9   10   11   12

> cbind(d1, d2, d3)
d1 d2 d3
[1,]  1  5  9
[2,]  2  6 10
[3,]  3  7 11
[4,]  4  8 12

The rows or columns have names taken from the original vector names. You can also use the commands to add rows or columns to an existing matrix, as long as the dimensions are appropriate:

> mat <- cbind(d1, d2, d3)
> mat
     d1 d2 d3
[1,]  1  5  9
[2,]  2  6 10
[3,]  3  7 11
[4,]  4  8 12

> cbind(mat, d1)
     d1 d2 d3 d1
[1,]  1  5  9  1
[2,]  2  6 10  2
[3,]  3  7 11  3
[4,]  4  8 12  4

You can alter the names of the rows and columns afterwards.

Comments are closed.