我在 R 中编码,我有一个包含数据的 3 维数组(示例中的 ab)。然后我有一个矩阵,其中包含第三个数组维度 (idx) 的索引。该矩阵具有与数组相同的行数和列数。我想使用 idx 中包含的索引从数组中提取数据,以获得具有相同维度 idx 的矩阵。请看下面的例子:
a <- c(1:9)
b <- rev(a)
#array of data
ab <- array(c(a,b), dim = c(3,3,2))
ab
, , 1
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
, , 2
[,1] [,2] [,3]
[1,] 9 6 3
[2,] 8 5 2
[3,] 7 4 1
#matrix of indices
idx <- matrix(sample(1:2,9,replace=TRUE), nrow = 3)
idx
[,1] [,2] [,3]
[1,] 2 2 2
[2,] 2 1 1
[3,] 1 1 1
#now I want to get the following matrix:
[,1] [,2] [,3]
[1,] 9 6 3
[2,] 8 5 8
[3,] 3 6 9
#these two don´t do the job
ab[idx]
ab[ , ,idx]
有谁知道我怎么能得到它?
非常感谢!
萨拉
最佳答案
我们需要行/列的索引和第三维(来自“idx”)来提取元素。我们通过 cbind
使用 'idx' 对行索引、列索引进行操作。
i1 <- dim(ab)[1]
j1 <- dim(ab)[2]
matrix(ab[cbind(rep(seq_len(i1), j1),rep(seq_len(j1), each = i1), c(idx))], ncol=3)
# [,1] [,2] [,3]
#[1,] 9 6 3
#[2,] 8 5 8
#[3,] 3 6 9
关于arrays - R:从数组中提取矩阵,使用索引矩阵,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39344473/