我正在使用R进行编码,我有一个包含数据的三维数组(例如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]
有人知道我怎么能得到它吗?
非常感谢!
Sara