Bind dimensions of an array

Viewed 71

Let's start with an exemplary multi-dimensional array like

a <- array(1:24, dim = c(3, 2, 2, 2)); a

, , 1, 1

     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

, , 2, 1

     [,1] [,2]
[1,]    7   10
[2,]    8   11
[3,]    9   12

, , 1, 2

     [,1] [,2]
[1,]   13   16
[2,]   14   17
[3,]   15   18

, , 2, 2

     [,1] [,2]
[1,]   19   22
[2,]   20   23
[3,]   21   24

Now I want to cbind or rbind the first two dimensions, which are matrices over the remaining dimensions 3 and 4, to an entire data.frame.

The resulting data.frame should like this using rbind:

       [,1]  [,2]
[1, ]   1      4
[2, ]   2      5
[3, ]   3      6
[4, ]   7      10
[5, ]   8      11
[6, ]   9      12
...

What would be an efficient way to bind the first two dimensions of a multi-dimensional array to an entire structure like data.frame? Please consider that the array can have any number of dimensions greater than 2, and not only 4 like in the above given example.

Thanks in advance

2 Answers

Permuting and modifying dimensions is quite efficient:

a <- array(1:24, dim = c(3, 2, 2, 2))

a <- aperm(a, c(2, 1, 3, 4))
dim(a) <- c(dim(a)[1], prod(dim(a)[-1]))
t(a)

#      [,1] [,2]
# [1,]    1    4
# [2,]    2    5
# [3,]    3    6
# [4,]    7   10
# [5,]    8   11
# [6,]    9   12
# [7,]   13   16
# [8,]   14   17
# [9,]   15   18
#[10,]   19   22
#[11,]   20   23
#[12,]   21   24

You can use apply:

apply(a, 2, identity)
#      [,1] [,2]
# [1,]    1    4
# [2,]    2    5
# [3,]    3    6
# [4,]    7   10
# [5,]    8   11
# [6,]    9   12
# [7,]   13   16
# [8,]   14   17
# [9,]   15   18
#[10,]   19   22
#[11,]   20   23
#[12,]   21   24
Related