Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Shuffle array elements of selected dimensions

Problem: Given a multidimensional array, shuffle its elements in some selected dimensions. Ideally, the array should be shuffled in situ / in place, because a second one might not fit into my memory.

For example, given an array a with 4 dimensions, assign to each a[x,y,z,] another value a[x2,y2,z2,] for all x,y,z, where x2,y2,z2 are chosen randomly from the set of indices of their respective dimension.

Example array:

set.seed(1)
a <- array(data=sample(1:9, size=3*3*3*2, replace=T), dim=c(3,3,3,2))

Is there a more efficient way to do this in R than using 3 nested for-loops? The naive approach I tried:

x.rand <- floor(runif( n=3, min = 1, max = 3 + 1)); # max and min will not be generated by runif()
y.rand <- floor(runif( n=3, min = 1, max = 3 + 1));
z.rand <- floor(runif( n=3, min = 1, max = 3 + 1));
for( i in 1:3) {
  for( j in 1:3) {
    for( k in 1:3) {
      tmp <- a[i,j,k, ];
      a[i,j,k,] <- a[x.rand[i], y.rand[j], z.rand[k], ];
      a[x.rand[i], y.rand[j], z.rand[k], ] <- tmp;
    }
  }
}

But for larger arrays I run into performance issues.

like image 986
user1694351 Avatar asked Nov 26 '25 05:11

user1694351


1 Answers

I think Pop had the right idea before he removed his answer but you'll have to be careful to use sample if you don't want to drop data (we're not swapping "columns" two-by-two anymore but selecting all of them once in a different order)

x.rand <- sample(dim(a)[1])
y.rand <- sample(dim(a)[2])
z.rand <- sample(dim(a)[3])
a[] <- a[x.rand, y.rand, z.rand, ]

Assuming an array with larger dimensions, a more programmatic approach could be:

idx <- lapply(dim(a), sample) # shuffle dimensions
idx[[4]] <- TRUE  # the only fixed dimension
a[] <- do.call(`[`, c(list(a), idx))
like image 180
flodel Avatar answered Nov 28 '25 19:11

flodel