问题
I'm trying to find the row positions of a sequence. By that I mean the following:
x<-c(-1,1)
y<-c(1,-1,1,0,-1,0,0)
match(x,y)
[1] 2 1
Why doesn't this return 2 3 ? (That's what I want it to do)
If I do this:
y<-c(0,-1,1,0,-1,0,0)
match(x,y)
[1] 2 3
it works. Advice?
回答1:
Here's an idea. imatch()
will find all the matched indices, in case there is more than one set of matches. It does this by checking two successive indices, one pair at a time, and checking if they are identical to the x
vector. Non-matches are removed, and a list of matches returned.
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
回答2:
Maybe a little convoluted but worth being noted just in case of:
m <- regexpr(paste0(x,collapse=""),paste0(z,collapse = ""),fixed=T)
seq(m,length.out=length(x))
The idea is to turn each vector in the text string and then found where the first string is in the second.
The match position give the starting postion, the lenght of the first vector gives how much indices we should return.
Drawback it will break with values above 9.
Edit to explain why it may fail:
> x2 <- c(3,4)
> y2 <- c(1,34,5)
> m <- regexpr(paste0(x2,collapse=""),paste0(y2,collapse = ""),fixed=T)
> seq(m,length.out=length(x))
[1] 2 3
It match two position but it should not match.
来源:https://stackoverflow.com/questions/33418495/how-do-i-return-the-row-index-of-a-sequence-in-r