获取另一个向量中数字向量的索引 [英] Get indexes of a vector of numbers in another vector

查看:53
本文介绍了获取另一个向量中数字向量的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下向量:

v <- c(2,2,3,5,8,0,32,1,3,12,5,2,3,5,8,33,1)

给定一个数字序列,例如 c(2,3,5,8),我试图找出这个数字序列在向量 v 中的位置.我期望的结果是这样的:

Given a sequence of numbers, for instance c(2,3,5,8), I am trying to find what is the position of this sequence of numbers in the vector v. The result I expect is something like:

FALSE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE FALSE FALSE 

我正在尝试使用 which(v == c(2,3,5,8)) 但它没有给我我想要的东西.

I am trying to use which(v == c(2,3,5,8)) but it doesn't give me what I am looking for.

先谢谢了.

推荐答案

使用基础 R,您可以执行以下操作:

Using base R you could do the following:

v <- c(2,2,3,5,8,0,32,1,3,12,5,2,3,5,8,33,1)
x <- c(2,3,5,8)

idx <- which(v == x[1])
idx[sapply(idx, function(i) all(v[i:(i+(length(x)-1))] == x))]
# [1]  2 12

这告诉您确切的序列出现了两次,从向量 v 的位置 2 和 12 开始.

This tells you that the exact sequence appears twice, starting at positions 2 and 12 of your vector v.

它首先检查可能的起始位置,即 v 等于 x 的第一个值,然后循环遍历这些位置以检查这些位置之后的值是否也相等x 的其他值.

It first checks the possible starting positions, i.e. where v equals the first value of x and then loops through these positions to check if the values after these positions also equal the other values of x.

这篇关于获取另一个向量中数字向量的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆