Camford Oxbridge
Camford Oxbridge

Reputation: 894

Combine 3-dimensional array to 2-dimensional array in R

Let a be an array as follows.

 a <- array(1:24,c(2,3,4))
> a
, , 1

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

, , 2

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

, , 3

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

, , 4

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

What I want is the following new array b which is obtained by combining along the third index.

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

Upvotes: 1

Views: 52

Answers (1)

Jan
Jan

Reputation: 5254

There is another solution using rbind.

z <- 4
a <- array(1:(2*3*z),c(2,3,z))
rbind(a[,,1], a[,,2], a[,,3], a[,,4])
#>      [,1] [,2] [,3]
#> [1,]    1    3    5
#> [2,]    2    4    6
#> [3,]    7    9   11
#> [4,]    8   10   12
#> [5,]   13   15   17
#> [6,]   14   16   18
#> [7,]   19   21   23
#> [8,]   20   22   24

This solution can be generalized with apply to be used in cases with z != 4:

apply(a, 2, rbind, deparse.level = 0)
#>      [,1] [,2] [,3]
#> [1,]    1    3    5
#> [2,]    2    4    6
#> [3,]    7    9   11
#> [4,]    8   10   12
#> [5,]   13   15   17
#> [6,]   14   16   18
#> [7,]   19   21   23
#> [8,]   20   22   24

A quick benchmark between these solutions gave the warning Could not measure a positive execution time for 3565 evaluations. That happens when execution times are so fast they cannot be measured by microbenchmark. I checked and the failed measurements were distributed rather equally. In essence, it seems that none of these solutions has an obious advantage in performance, even when I tried much larger arrays.

Created on 2021-01-09 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions