Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

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
question from:https://stackoverflow.com/questions/65641221/combine-3-dimensional-array-to-2-dimensional-array-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...