如何返回R中序列的行索引?

JK_*_*own 0 r match

我正试图找到一个序列的行位置.我的意思是:

x<-c(-1,1)
y<-c(1,-1,1,0,-1,0,0)
match(x,y)
[1] 2 1
Run Code Online (Sandbox Code Playgroud)

为什么不返回2 3?(这就是我想要的)

如果我这样做:

y<-c(0,-1,1,0,-1,0,0)
match(x,y)
[1] 2 3
Run Code Online (Sandbox Code Playgroud)

有用.建议吗?

Ric*_*ven 5

这是一个想法. imatch()将找到所有匹配的索引,以防有多组匹配.它通过检查两个连续的索引,一次一对,并检查它们是否与x向量相同来完成此操作.删除不匹配,并返回匹配列表.

imatch <- function(x, y) {
    Filter(
        Negate(is.null), 
        lapply(seq_along(length(y)-1), function(i) {
            ind <- i:(i+1)
            if(identical(y[ind], x)) ind 
        })
    )
}

imatch(c(-1, 1), c(1, -1, 1, 0, -1, 0, 0))
# [[1]]
# [1] 2 3

imatch(c(-1, 1), c(1, -1, 1, 0, -1, 1, 0))
# [[1]]
# [1] 2 3
#
# [[2]]
# [1] 5 6
Run Code Online (Sandbox Code Playgroud)