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.na
to 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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…