[英]Is there an R function finding a vector within another vector?
For example, I have two vectors:例如,我有两个向量:
x1 <- c(0,1,2)
x2 <- c(1,2,0,1,2,3,4,5,0,1,0,1,2)
I would like to find the position where x1 is first present x2, which is in this case is 3. I have tried which(), match(), but both seems to find elements, instead of vectors.我想找到 x1 首先出现 x2 的位置,在这种情况下是 3。我尝试过 which()、match(),但两者似乎都找到了元素,而不是向量。 Is there a R function that can achieve this or a way to construct one?是否有 R 函数可以实现这一点或构建一个方法?
Thank you!谢谢!
If you are looking for the first match of 0
:如果您正在寻找0
的第一场比赛:
match(x1[1], x2)
But for the whole vector:但是对于整个向量:
> which(apply(t(embed(x2, length(x1))) == rev(x1), 2, all))[1]
[1] 3
>
Edit:编辑:
To give NA
on no-match:在不匹配时给出NA
:
cond <- apply(t(embed(x2, length(x1))) == rev(x1), 2, all)
if (any(cond)) which(cond)[1] else NA
This uses embed
to split x2
into chunks by the length of x1
, and it applies it and detects whether it is equivalent to x1
, and gives a boolean vector (or TRUE
s and FALSE
s).这使用embed
按x1
的长度将x2
拆分为块,并应用它并检测它是否与x1
等效,并给出一个布尔向量(或TRUE
s 和FALSE
s)。 Then finally it uses which
to get the index of the occurrences of TRUE
, and I use [1]
to get the first value.最后它使用which
来获取TRUE
出现的索引,我使用[1]
来获取第一个值。
For the edit, I detect if in the conditioned boolean vector contains any TRUE
s, if so, do the same thing as mentioned above, if not, give NA
.对于编辑,我检测条件布尔向量中是否包含任何TRUE
s,如果是,则执行上述相同的操作,如果没有,则给出NA
。
One option would be to do rolling comparison.一种选择是进行滚动比较。
x1 <- c(0,1,2)
x2 <- c(1,2,0,1,2,3,4,5,0,1,0,1,2)
which(zoo::rollapply(x2, length(x1), function(x) all(x == x1)))
#[1] 3 11
To get the 1st occurrence -要获得第一次出现 -
which(zoo::rollapply(x2, length(x1), function(x) all(x == x1)))[1]
#[1] 3
For all elements for vector x1.对于向量 x1 的所有元素。
sapply(x1, function(x) match(x,x2))
[1] 3 1 2
Another approach with stringr
; stringr
另一种方法;
library(tidyverse)
x1_ <- paste0(x1,collapse="")
x2_ <- paste0(x2,collapse="")
str_locate_all(x2_, x1_)[[1]]
gives,给,
start end
[1,] 3 5
[2,] 11 13
which returns empty if there is no match.如果没有匹配,则返回空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.