开发者

Finding list of positions in multidimensional structure (array)

Suppose I have a simple multidimensio开发者_JAVA技巧nal structure, like this one:

somestr<-array(sample.int(2, 120, replace=TRUE), dim=c(4,5,6))

I'm looking for all positions in the structure (in this case, an array) where the value is equal to, say for my example, 2. Note that the structure might just as well hold characters or logicals. For now, it will do to just find all values equal to a given, but it would be nice to extend the idea to any logical-valued function that can be applied to each item in the structure (That would allow e.g. is.nato be used).

What I would like to get, is an (integer) matrix with as many columns as somestr has dimensions (in this case 3), and as many rows (depends on the sample.int call above) as there are values equal to the given value (2). The values in this new matrix are the 'coordinates' within somestr where the values are equal to 2.

I apologize for mixing my example with the explanation, but I was hoping it would be clearer that way. For the record: I'm able to produce this myself (may even answer my own question), but I was hoping for a standardized solution (read: a readymade function in some package), or learn new tricks along the way.

So, in short, can you write a function

posOf<-function(somestr, valueToCompareTo)

that returns a matrix of the positions in somestr equal to valueToCompareTo, and if valueToCompareTo is a function, the positions in somestr for which applying this function returns TRUE.


I think the which function can do that:

which(somestr==2, arr.ind=TRUE)

(if I understood everything correctly)

R> set.seed(123)
R> somestr <- array(sample.int(2, 120, replace=TRUE), dim=c(4,5,6))
R> somestr
, , 1

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

...

, , 6

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

R> which(somestr==2, arr.ind=TRUE)
      dim1 dim2 dim3
 [1,]    2    1    1
 [2,]    4    1    1
 [3,]    1    2    1
 [4,]    3    2    1
 [5,]    4    2    1
...
[57,]    2    5    6
[58,]    3    5    6
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜