查找数组元素的维度索引

时间:2014-10-17 20:57:09

标签: arrays r

考虑这个数组:

the.seq <- 1:4
sol<- outer(outer(the.seq, the.seq, `+`), the.seq, `+`)

我想找到所有和6的元素。这对于which非常容易:

indices <- which(sol == 6)
indices
 [1]  4  7 10 13 19 22 25 34 37 49

现在我想要一个带有这些元素的维度索引的向量,答案是:

      [,1] [,2] [,3]
 [1,]    4    1    1
 [2,]    3    2    1
 [3,]    2    3    1
 [4,]    1    4    1
 [5,]    3    1    2
 [6,]    2    2    2
 [7,]    1    3    2
 [8,]    2    1    3
 [9,]    2    1    3
[10,]    1    1    4

你会怎么做?

1 个答案:

答案 0 :(得分:3)

您可以使用arr.ind中的which参数。设置为TRUE时,which将返回其第一个参数为TRUE的数组索引。

which(sol == 6, arr.ind = TRUE)
#      dim1 dim2 dim3
# [1,]    4    1    1
# [2,]    3    2    1
# [3,]    2    3    1
# [4,]    1    4    1
# [5,]    3    1    2
# [6,]    2    2    2
# [7,]    1    3    2
# [8,]    2    1    3
# [9,]    1    2    3
#[10,]    1    1    4