BLe*_*evy 2 r sequence pattern-matching indices
假设我有序列:
x = c( 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0)
Run Code Online (Sandbox Code Playgroud)
在R中是否有一种优雅的方式来返回每个序列1的开始和停止索引?
答案应该是一个2列数组,其中nRows = 1的序列数:
startIndx = [ 1, 5, 7 ]
stopIndex = [ 2, 5, 9 ]
Run Code Online (Sandbox Code Playgroud)
谢谢.
BSL
假设您的向量包含0和1值:
which(diff(c(0L, x)) == 1L)
#[1] 1 5 7
which(diff(c(x, 0L)) == -1L)
#[1] 2 5 9
Run Code Online (Sandbox Code Playgroud)
否则你需要先做的事情x <- x == 1L.
优雅的方式是
y <- which(x==1)
startIndx <- y[!(y-1) %in% y]
stopIndex <- y[!(y+1) %in% y]
rbind(startIndx, stopIndex)
# [,1] [,2] [,3]
#startIndx 1 5 7
#stopIndex 2 5 9
Run Code Online (Sandbox Code Playgroud)