查找向量中多个元素的所有位置
假设我有以下向量:
x <- c(8, 6, 9, 9, 7, 3, 2, 5, 5, 1, 6, 8, 5, 2, 9, 3, 5, 10, 8, 2)
如何找到哪些元素是 8 或 9?
Suppose I have the following vector:
x <- c(8, 6, 9, 9, 7, 3, 2, 5, 5, 1, 6, 8, 5, 2, 9, 3, 5, 10, 8, 2)
How can I find which elements are either 8 or 9?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是一种方法。 首先,我得到 x 为 8 或 9 时的索引。然后我们可以验证在这些索引处,x 确实为 8 和 9。
This is one way to do it. First I get the indices at which x is either 8 or 9. Then we can verify that at those indices, x is indeed 8 and 9.
您可以尝试使用
|
运算符来获得简短的条件You could try the
|
operator for short conditions在这种特定情况中,您还可以使用
grep
:两者都会给出:
当您还想检测多于一位数字的数字时,第二个选项是首选:
但是,出于某种原因,我确实在回答开始时强调了这个具体案例。 正如 @DavidArenburg 提到的,这可能会导致导致意想不到的结果。 例如,使用
grep('1|8',x)
将检测1
和10
:为了避免这种副作用,您必须将要检测的数字包装在单词边界中:
现在,未检测到
10
。In this specific case you could also use
grep
:which both give:
When you also want to detect number with more than one digit, the second option is preferred:
However, I did put emphasis on this specific case at the start of my answer for a reason. As @DavidArenburg mentioned, this could lead to unintended results. Using for example
grep('1|8',x)
will detect both1
and10
:In order to avoid that side-effect, you will have to wrap the numbers to be detected in word-bounderies:
Now, the
10
isn't detected.这是查找所有目标值位置的通用解决方案(仅适用于向量和一维数组)。
此函数返回一个列表,因为每个目标可能有任意数量的匹配项,包括零个。 该列表按目标的原始顺序排序(并命名)。
这是一个使用中的例子:
Here is a generalized solution to find the locations of all target values (only works for vectors and 1-dimensional arrays).
This function returns a list because each target may have any number of matches, including zero. The list is sorted (and named) in the original order of the targets.
Here is an example in use:
或者,如果您不需要使用索引而只需要使用元素,您可以这样做
Alternatively, if you do not need to use the indices but just the elements you can do
如果您想使用循环找到答案,那么以下脚本将完成这项工作:
输出将如下所示:
这里, pos[[1]] 包含 8 的位置,pos[[2]] 包含 9 的位置。如果您使用 %in% 方法并更改元素的输入顺序,即 c(9,8) 而不是 c(8,9),则两者的输出将相同。 该方法缓解了这样的问题。
If you want to find the answer using loops, then the following script will do the job:
The output will look like this:
Here, pos[[1]] contains positions of 8 and pos[[2]] contains positions of 9. If you are using the %in% method and change the input order of elements, i.e, c(9,8) instead of c(8,9), the output will be the same for both of them. This method alleviates such problem.
grepl
也许是一个有用的函数。 请注意,grepl
出现在 R 2.9.0 及更高版本中。grepl
的便利之处在于它返回与x
长度相同的逻辑向量。要得到答案,您可以执行以下操作
grepl
maybe a useful function. Note thatgrepl
appears in versions of R 2.9.0 and later. What's handy aboutgrepl
is that it returns a logical vector of the same length asx
.To arrive at your answer, you could do the following