下面的代码应该在数组的各个级别之间交换列,但是它会导致超出范围的'下标。错误:
pop <- array(1:25, dim = c(5, 10, 2)) # 2-level array with 5 rows and 10 columns
m <- 0.20 # proportion of columns to swap
K <- 2
inds1 <- sample(ncol(pp), size = ceiling(ncol(x) * m), replace = FALSE) # sample random columns
inds2 <- sample(ncol(pop), size = ceiling(ncol(x) * m), replace = FALSE)
for (i in 1:K) { # swap columns between subarrays
for(j in 1:K) {
tmp <- pop[i,, inds1]
pop[i,, inds1] <- pop[j,, inds2]
pop[j,, inds2] <- tmp
}
}
Error in pop[i, , inds1] : subscript out of bounds
我想知道为什么R会在这里抛出一个错误。它也适用于任何n级数组。知道问题可能是什么?
答案 0 :(得分:1)
我认为问题在于x
的定义方式,子集是:
x[row, column, array level]
您正尝试访问阵列级别中的列。因此,如果您有inds1 = 3
,那么pop[i, ,inds1]
将尝试访问不存在的第三个数组。请参阅下面的工作示例。要解决您当前的示例,我们需要有关pop
和K
的更多信息:
x <- array(1:25, dim = c(5, 10, 2)) # 2-level array with 5 rows and 10 columns
m <- 0.20 # proportion of columns to swap
set.seed(1)
inds1 <- sample(ncol(x), size = ceiling(ncol(x) * m), replace = FALSE) # sample random columns
inds2 <- sample(ncol(x), size = ceiling(ncol(x) * m), replace = FALSE)
x
#, , 1
#
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#[1,] 1 6 11 16 21 1 6 11 16 21
#[2,] 2 7 12 17 22 2 7 12 17 22
#[3,] 3 8 13 18 23 3 8 13 18 23
#[4,] 4 9 14 19 24 4 9 14 19 24
#[5,] 5 10 15 20 25 5 10 15 20 25
#
#, , 2
#
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#[1,] 1 6 11 16 21 1 6 11 16 21
#[2,] 2 7 12 17 22 2 7 12 17 22
#[3,] 3 8 13 18 23 3 8 13 18 23
#[4,] 4 9 14 19 24 4 9 14 19 24
#[5,] 5 10 15 20 25 5 10 15 20 25
inds1;inds2
[1] 3 4
[1] 6 9
所以交换第3列和第3列6和4栏&amp;我们可以做到:
temp <- x[, inds1, 1]
x[,inds1, 1] <- x[,inds2, 2]
x[,inds2, 2] <- temp