Bind sheet rows in a 3d array to make a 2d array

I have a 3-dimensional array and would like to collapse to two-dimensional by stacking one dimension in rows (combining rows of one dimension). In my code, I filled out a โ€œworksheetโ€ (3rd dimension) with a 2-dimensional array for each index, and now I want to take this 3-dimensional array and collect the rows of these sheets one above the other.

Here is an example array, so I can explain what I want the final result to look like:

x <- array(1:24, dim=c(2, 3, 4),
           dimnames=list(letters[1:2], LETTERS[1:3], letters[23:26]))
dim(x)

I would like to w, x, y, zwere stacked on top of each other in a two-dimensional array, which would have 8 rows and 3 columns. Here is a way to do this, which is cumbersome (and not possible in my loop):

x1<-x[,,1]
x2<-x[,,2]
x3<-x[,,3]
x4<-x[,,4]

All<-rbind(x1,x2,x3,x4)

I looked abindand adrop, but they are not quite right.

aperm, , , (?)

list ( , , ). , ?

!

+4
2

, , , .

apply(x, 2, c)
#or if you're really pushing for speed, the simpler function:
apply(x, 2, identity)

# Giving:
#      A  B  C
#[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

:

all.equal(apply(x,2,c), All, check.attributes=FALSE)
#[1] TRUE
+4

, , :

y <- aperm(x, c(1, 3, 2))
dim(y) <- c(prod(dim(x)[-2]), dim(x)[2])
# the above evaluates to c(8, 3)

y

#      [,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    

colnames(y) <- colnames(x), .

+1

Source: https://habr.com/ru/post/1545007/


All Articles