57

When working with matrices in R, one can put them side-by-side or stack them top of each other using cbind and rbind, respectively. What is the equivalent function for stacking matrices or arrays in other dimensions?

For example, the following creates a pair of 2x2 matrices, each having 4 elements:

x = cbind(1:2,3:4)
y = cbind(5:6,7:8)

What is the code to combine them into a 2x2x2 array with 8 elements?

Ryan C. Thompson
  • 40,856
  • 28
  • 97
  • 159

1 Answers1

63

See the abind package. If you want them to bind on a 3rd dimension, do this:

library(abind)
abind(x, y, along = 3)

See ?abind

Also, abind gives a lot more convenience, but for simple binding you can just manipulate the values directly, based on the default ordering:

array(c(x, y), dim = c(2, 2, 2))
MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
mdsumner
  • 29,099
  • 6
  • 83
  • 91
  • There is also a function called `Abind` in the `DescTools` package. Looks almost identical to me. – Alison Bennett Jul 18 '18 at 07:40
  • 3
    If I want to add a new matrix, `z`, to an existing array, `my.array`, this seems to work: `array(c(my.array, z), dim = c(dim(my.array)[1], dim(my.array)[2], 3))` – Mark Miller Mar 20 '19 at 20:12