Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

r - Finding list of positions in multidimensional structure (array)

Suppose I have a simple multidimensional 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...