【发布时间】:2016-09-06 08:43:54
【问题描述】:
我在 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]
有人知道我怎样才能得到它吗?
非常感谢!
萨拉
【问题讨论】: