查找多维结构(数组)中的位置列表
假设我有一个简单的多维结构,如下所示:
somestr<-array(sample.int(2, 120, replace=TRUE), dim=c(4,5,6))
我正在寻找结构(在本例中为数组)中值等于 2 的所有位置。请注意,该结构可能只是以及保存字符或逻辑。目前,只需找到等于给定值的所有值即可,但最好将这个想法扩展到可以应用于结构中每个项目的任何逻辑值函数(这将允许例如 is .na
使用)。
我想要得到的是一个 (integer
) 矩阵,其列数与 somestr
的维度(在本例中为 3)一样多,以及行数(取决于上面的 example.int 调用),因为存在等于给定值 (2) 的值。这个新矩阵中的值是 somestr
中的“坐标”,其中值等于 2。
我很抱歉将我的示例与解释混合在一起,但我希望这样会更清楚。作为记录:我能够自己生成这个(甚至可以回答我自己的问题),但我希望有一个标准化的解决方案(阅读:某个包中的现成函数),或者一路学习新的技巧。
简而言之,您可以编写一个函数
posOf<-function(somestr, valueToCompareTo)
,返回 somestr
中等于 valueToCompareTo
的位置矩阵,并且如果 valueToCompareTo
是一个函数,somestr
中应用此函数返回 TRUE
的位置。
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
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为
which
函数可以做到这一点:(如果我理解正确的话)
I think the
which
function can do that:(if I understood everything correctly)