D1X
D1X

Reputation: 5444

How to combine a list of 3 dimensional arrays by its first dimension?

I have a list of 3D arrays which have the same number of elements in their second and third dimensions, which I need to convert to a single 3D array which contains every list element.

As a reproducible example:

m1 <- array(seq(1,12*5),c(3,4,5))
m2 <- array(seq(100,16*5+100),c(4,4,5))
RE <- list(m1, m2)

Then

> m1[1,,]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1   13   25   37   49
[2,]    4   16   28   40   52
[3,]    7   19   31   43   55
[4,]   10   22   34   46   58

And

> m2[4,,]
     [,1] [,2] [,3] [,4] [,5]
[1,]  103  119  135  151  167
[2,]  107  123  139  155  171
[3,]  111  127  143  159  175
[4,]  115  131  147  163  179

I need to have it as a single 3D array M, starting with M[1,,] = m1[1,,] and ending with M[7,,] = m2[4,,].

Upvotes: 1

Views: 404

Answers (1)

MrFlick
MrFlick

Reputation: 206167

This is easier with the abind() function from the abind package. Try

library(abind)
M <- abind(m1, m2, along=1)
# or, using the list
M <- do.call("abind", c(RE, along=1))

Upvotes: 2

Related Questions