在 R returns 'subscript out of bounds' 中交换列

Swapping columns in R returns 'subscript out of bounds'

以下代码应该在数组的级别之间交换列,但会导致 'subscript out of bounds' 错误:

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 级数组。知道问题出在哪里吗?

我认为问题在于 x 的定义方式,子集是:

x[row, column, array level]

您正在尝试访问数组级点中的列。因此,如果您有例如 inds1 = 3,那么 pop[i, ,inds1] 将尝试访问不存在的第三个数组。请参阅下面的工作示例。为了解决您当前的示例,我们需要有关 popK:

的更多信息
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 列和第 6 列以及第 4 列和第 9 列,我们可以这样做:

temp <- x[, inds1, 1]
x[,inds1, 1] <- x[,inds2, 2]
x[,inds2, 2] <- temp