如何获取 R 中多个连续元素的索引?

How to get an index of multiple consecutive elements in R?

我有两个长列表,其中一个是另一个的连续子集。 示例:

full= c("cat", "dog", "giraffe", "gorilla", "opossum", "rat")
subset= c("giraffe", "gorilla", "opossum")

有没有一种优雅的方法来获取匹配开始、结束或两者的索引? 在上面的例子中,我想得到 3 因为它是 "giraffe" 的全文索引?

澄清一下,如果 subset= c("giraffe", "rat", "gorilla", "opossum") 输出应该是 NA。

zoo::rollapply(full, 3, FUN = identical, subset)
# [1] FALSE FALSE  TRUE FALSE
which(zoo::rollapply(full, 3, FUN = identical, subset))[1]
# [1] 3
zoo::rollapply(full, 3, FUN = func, c("giraffe", "rat", "gorilla", "opossum"))
# [1] FALSE FALSE FALSE FALSE
which(zoo::rollapply(full, 3, FUN = identical, c("giraffe", "rat", "gorilla", "opossum")))[1]
# [1] NA

我们可能需要 match 条件

f1 <- function(subvec, fullvec) {
     i1 <- match(subvec, fullvec, nomatch = 0)
     if(any(diff(i1) != 1)) NA else i1[1]
}

-测试

> f1(subset, full)
[1] 3
> f1(subset2, full)
[1] NA
> f1(subset[c(1, 3)], full)
[1] NA

数据

full <- c("cat", "dog", "giraffe", "gorilla", "opossum", "rat")
subset <-  c("giraffe", "gorilla", "opossum")
subset2 <-  c("giraffe", "rat", "gorilla", "opossum")