问题:给定一个多维数组,在某些选定的维度中打乱其元素。理想情况下,数组应该就地/就地进行洗牌,因为第二个数组可能不适合我的内存。
例如,给定一个 4 维数组 a
,为每个 a[x,y,z,]
分配另一个值 a[x2,y2 ,z2,]
对于所有 x,y,z
,其中 x2,y2,z2
是从其各自维度的索引集中随机选择的。
数组示例:
set.seed(1)
a <- array(data=sample(1:9, size=3*3*3*2, replace=T), dim=c(3,3,3,2))
在 R 中是否有比使用 3 个嵌套 for 循环更有效的方法?我尝试过的天真的方法:
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;
}
}
}
但是对于更大的数组,我遇到了性能问题。
最佳答案
我认为 Pop 在删除答案之前有正确的想法,但如果您不想删除数据,则必须小心使用 sample
(我们不会交换“列” “不再是两两,而是以不同的顺序选择所有它们一次)
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, ]
假设数组具有更大的维度,更具编程性的方法可能是:
idx <- lapply(dim(a), sample) # shuffle dimensions
idx[[4]] <- TRUE # the only fixed dimension
a[] <- do.call(`[`, c(list(a), idx))
关于R:随机排列选定维度的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27187872/