本文介绍了如何在R中返回序列的行索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试查找序列的行位置.我的意思是:
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
为什么这不返回2 3? (这就是我想要的)
Why doesn't this return 2 3 ? (That's what I want it to do)
如果我这样做:
y<-c(0,-1,1,0,-1,0,0)
match(x,y)
[1] 2 3
有效.咨询吗?
推荐答案
这是个主意.如果有多个匹配项,imatch()
将找到所有个匹配的索引.它通过检查两个连续的索引(一次一对)并检查它们是否与x
向量相同来做到这一点.不匹配项将被删除,并返回匹配项列表.
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
这篇关于如何在R中返回序列的行索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!