开发者

Transform a 3D array into a matrix in R

开发者 https://www.devze.com 2023-01-21 19:25 出处:网络
I\'m trying to transform a 3D array into a matrix. I want the third dimension of the array to form the first row in the matrix, and this third dimension should be read by row (i.e., row 1, then row 2

I'm trying to transform a 3D array into a matrix. I want the third dimension of the array to form the first row in the matrix, and this third dimension should be read by row (i.e., row 1, then row 2 etc... of dimension 3 should make up the first row of the matrix). I've given an example below, where the array has dimensions of 4, 3, and 5, and the resulting matrix has 5 rows and 12 columns. I have a solution below that achieves what I want, but it seems very cumbersome for large arrays (it first creates vectors from the elements of the array (by row), and then rbinds these to form the matrix). Is there a more elegant way to do this? Thanks in advance for any suggestions.

dat <- array( rnorm(60), d开发者_StackOverflow社区im=c(4, 3, 5) )   

results <- list(1:5)            
for (i in 1:5) {  
    vec <- c( t(dat[, , i]) )  
    results[[i]] <- vec  
    }

datNew <- rbind( results[[1]], results[[2]], results[[3]], results[[4]], results[[5]] )  


Use aperm

X <- aperm(dat,c(3,2,1))
dim(X)<- c(5, 12)


One line answer:

t(apply(dat,3,"c"))
0

精彩评论

暂无评论...
验证码 换一张
取 消