2016-11-11 68 views
0

我想根据多个值获取R中三维数组的索引(即arr [x,y,z])。具体来说,使用第一个z维来对第二个z维中的值进行子集分类。这里是一个例子:根据多个值返回R中三维数组的索引

# 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 

其中()返回对应于 “a” 和 “c” 的,而不是矩阵索引(第(x,y)的位置)在M1的位置的矢量。我想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 

如果我做了这()子更简单,它不会返回指数:

#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 

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

+0

另请参阅'?arrayInd'; 'arrayInd(ac.ind,dim(arr)[1:2])' –

回答

1

问题是arr[,,1] %in% c("a", "c")返回一个向量。一种方法是用行等于的arr第一维度的数量施放此作为matrix

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 
+0

谢谢!这是我正在寻找的。 – ken

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