基于多个值返回R中的3D数组的索引

时间:2016-11-11 14:14:47

标签: arrays r

我想基于多个值获得R中的3D数组的索引(即arr [x,y,z])。具体而言,使用第一个z维度来对第二个z维度中的值进行子集化。这是一个例子:

 # create example array
 > m1 <- matrix(c(rep("a",5), rep("b",5), rep("c",5)), nr = 5)  
 > m2 <- matrix(c(rep(100, 5), rep(10, 5), rep(10, 5)), nr = 5)
 > arr <- array(c(m1, m2), dim = c(dim(m1), 2))

 #use which() to return the indices in m2 that correspond to indices with
 #"a" and "c" values in m1.  This does not work as expected.
 > ac.ind <- which(arr[,,1] %in% c("a", "c"), arr.ind = T)

 > ac.ind
 [1]  1  2  3  4  5 11 12 13 14 15

which()返回m1中对应于“a”和“c”的位置向量,而不是矩阵索引((x,y)位置)。我想ac.ind回来:

           row col
      [1,]   1   1
      [2,]   2   1
      [3,]   3   1
      [4,]   4   1
      [5,]   5   1
      [1,]   1   3
      [2,]   2   3
      [3,]   3   3
      [4,]   4   3
      [5,]   5   3

如果我做一个更简单的which()子集,它确实返回索引:

 #use which to return indices in m2 that correspond to only "a" in m1
 >a.ind <- which(arr[,,1] == c("a"), arr.ind = T)

 >a.ind
      row col
 [1,]   1   1
 [2,]   2   1
 [3,]   3   1
 [4,]   4   1
 [5,]   5   1

我正在使用%in%,因为我想根据m1中的两个值进行子集(“a”和“c”值)。有没有办法根据R中的两个值返回数组的索引?

2 个答案:

答案 0 :(得分:1)

问题是arr[,,1] %in% c("a", "c")会返回一个向量。一种方法是将其转换为matrix,其行数等于arr的第一维:

ac.ind <- which(matrix(arr[,,1] %in% c("a", "c"), nrow=dim(arr)[1]), arr.ind = T)
##      row col
## [1,]   1   1
## [2,]   2   1
## [3,]   3   1
## [4,]   4   1
## [5,]   5   1
## [6,]   1   3
## [7,]   2   3
## [8,]   3   3
## [9,]   4   3
##[10,]   5   3

答案 1 :(得分:1)

这样的东西,但效率不高,因为它必须经过两次数据:

ac.ind <- which(arr[,,1] == "c" | arr[,,1] == "a" , arr.ind = T)

ac.ind

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