在 R 中交换列将返回'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

相关内容

最新更新