R - 从矩阵中提取满足给定条件的行?
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 1
[3,] 0 1 0
[4,] 0 0 1
[5,] 1 0 0
给定一个像上面这样的矩阵 - 迭代矩阵的有效方法是什么,选择第一个元素为 1 且所有其他元素为 0 的行,以便
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 1 0 0
返回?
谢谢, D .
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 1
[3,] 0 1 0
[4,] 0 0 1
[5,] 1 0 0
Given a matrix like that above - what is an efficient way to iterate over the matrix, selecting rows for which the first element is 1 and all other elements are 0, such that
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 1 0 0
is returned?
Thanks,
D.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
重新创建数据:
现在创建一个等于条件的向量。
接下来,包装在对
which
的调用中的apply
语句将告诉您哪些行符合您的条件最后,提取满足此条件的行:
生成的数组不'包含很多信息。也许您想知道有多少行符合条件?
来回答下一个问题。当数组很大时如何创建条件向量?
嗯,一种方法如下。假设您有一个 100 列宽的数组,因此您需要一个长度为 100 的向量,并且您希望第三个元素为 1:
Recreate the data:
Now create a vector that equals the condition.
Next, an
apply
statement wrapped in a call towhich
will tell you which rows match your conditionFinally, to extract the rows where this condition is met:
The resulting array doesn't contain much information. Perhaps you wanted to know how many rows match the condition?
To answer the follow-on question. How to create a condition vector when the array is large?
Well, one way is as follows. Let's say you have an array of 100 columns wide, so you need a vector of 100 in length, and you want the third element to be a 1: