Reputation: 249
I apologize since I don't know if theres and specific way to ask this. To simplify everything, I have the following array:
set.seed(4)
data <- array(rexp(12), dim=c(3,2,2))
, , 1
[,1] [,2]
[1,] 0.1716006 0.8026470
[2,] 4.3039449 0.6271484
[3,] 0.8681056 0.7348583
, , 2
[,1] [,2]
[1,] 0.44881179 0.8371497
[2,] 0.05069988 2.6802979
[3,] 0.50935005 0.2880769
And I want to obtain an array with [6,2] dimensions like this:
, 1
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0.1716006 0.8026470 4.3039449 0.6271484 0.8681056 0.7348583
, 2
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0.44881179 0.8371497 0.05069988 2.6802979 0.50935005 0.2880769
I would like to do this with a for loop since my arrays have [633,333,12] dimensions but everything is welcomed.
Upvotes: 2
Views: 72
Reputation: 26343
We could use aperm
to permute data
, where we change the first dimension and second dimension of the array:
data <- aperm(data, perm = c(2, 1, 3))
data
#, , 1
#
# [,1] [,2] [,3]
#[1,] 0.1716006 4.3039449 0.8681056
#[2,] 0.8026470 0.6271484 0.7348583
#
#, , 2
#
# [,1] [,2] [,3]
#[1,] 0.4488118 0.05069988 0.5093501
#[2,] 0.8371497 2.68029789 0.2880769
Now change its dimension with dim<-
dim(data) <- c(1, 6, 2)
data
#, , 1
#
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 0.1716006 0.802647 4.303945 0.6271484 0.8681056 0.7348583
#
#, , 2
#
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 0.4488118 0.8371497 0.05069988 2.680298 0.5093501 0.2880769
Upvotes: 2
Reputation: 20085
An option can be as using 3rd dimension of data
as:
sapply(1:dim(data)[3],function(x)t(data[,,x]))
# [,1] [,2]
# [1,] 0.1716006 0.44881179
# [2,] 0.8026470 0.83714966
# [3,] 4.3039449 0.05069988
# [4,] 0.6271484 2.68029789
# [5,] 0.8681056 0.50935005
# [6,] 0.7348583 0.28807690
Upvotes: 0