R:使用索引矩阵从数组中提取矩阵 [英] R: extract matrix from array, using a matrix of indices
问题描述
我用R编码,我有一个三维数组,其中包含数据(本例中为ab).然后,我有一个矩阵,其中包含第3个数组维数(idx)的索引.该矩阵具有相同数量的行和列的数组.我想使用idx中包含的索引从数组中提取数据,以获得与idx尺寸相同的矩阵.请参见下面的示例:
I´m coding in R and I have a 3 dimensional array that contains data (ab in the example). Then I have a matrix that contains indices of the 3rd array dimension (idx). This matrix has the same number of rows and columns of the array. I want to use the indices contained in idx to extract data from the array, to get a matrix with same dimension of idx. Please see the example below:
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]
有人知道我怎么得到吗?
Does anybody know how can I get that?
非常感谢!
萨拉
推荐答案
我们需要行/列的索引和第三个维度(来自"idx")以提取元素.我们通过cbind
使用'idx'来对行索引,列索引进行操作.
We need an index for row/column and the third dimension (from 'idx') to extract the elements. We do this by cbind
ing the row index, column index with the '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
这篇关于R:使用索引矩阵从数组中提取矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!