我在R中编码,并且我有一个包含数据的3维数组(在本例中为ab)。然后我有一个包含第三个数组维度(idx)索引的矩阵。该矩阵具有相同数量的行和列数组。我想使用idx中包含的索引从数组中提取数据,以获得具有相同维度idx的矩阵。请看下面的例子:R:使用索引矩阵从数组中提取矩阵
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]
有没有人知道我怎么能得到它?
非常感谢!
萨拉