0

Given the following array in R:

x <- 1:24
dim(x) <- c(2, 4, 3)

Which gives:

> x
, , 1

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

, , 2

     [,1] [,2] [,3] [,4]
[1,]    9   11   13   15
[2,]   10   12   14   16

, , 3

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

How to apply the sample() function to permute the columns across the matrices ? For instance in column 1, the value 1, 2, 9, 10 and 17, 18 would be permuted across the 3 matrices while staying in column 1.

One sampling could be:

> x
, , 1

     [,1] [,2] [,3] [,4]
[1,]    10    11    5    23
[2,]    2    19    22    8

, , 2

     [,1] [,2] [,3] [,4]
[1,]    1   3   6   24
[2,]   17   12   14   16

, , 3

     [,1] [,2] [,3] [,4]
[1,]   9   4   21   7
[2,]   18   20   13   15

2 Answers 2

2

It's easy when we transpose.

> set.seed(666)
> aperm(aperm(x, c(1, 3, 2))[sample.int(dim(x)[1]), sample.int(dim(x)[3]), ], c(1, 3, 2))
, , 1

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

, , 2

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

, , 3

     [,1] [,2] [,3] [,4]
[1,]   10   12   14   16
[2,]    9   11   13   15
Sign up to request clarification or add additional context in comments.

6 Comments

Sorry if it was unclear but here 7 and 8 values are now in column 2 while they were initially in column 4. They should stay in column 4 but be dispatched in x[,,1], x[,,2] or x[,,3].
@dputhier See update.
Not that readable but thanks for posting this solution.
@dputhier You wanted an efficient solution.
That's it. Thanks
|
1

I found this solution with a for loop but there is probably better and more efficient with large arrays (?)

     for(i in 1:ncol(x)){x[,i,] <- sample(x[,i,])}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.