在R中按顺序查找启动和停止索引
假设我有序列:在R中按顺序查找启动和停止索引,r,pattern-matching,sequence,indices,R,Pattern Matching,Sequence,Indices,假设我有序列: x = c( 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0) 在R中是否有一种优雅的方法来返回每个1序列的开始和停止索引 答案应该是一个2列数组,nRows=1的序列数: startIndx = [ 1, 5, 7 ] stopIndex = [ 2, 5, 9 ] 谢谢 BSL这个怎么样: startIndx<-rev(length(x)-cumsum(rle(rev(x))$lengths)[rle(rev(x))$values==1]+1) st
x = c( 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0)
在R中是否有一种优雅的方法来返回每个1序列的开始和停止索引
答案应该是一个2列数组,nRows=1的序列数:
startIndx = [ 1, 5, 7 ]
stopIndex = [ 2, 5, 9 ]
谢谢
BSL这个怎么样:
startIndx<-rev(length(x)-cumsum(rle(rev(x))$lengths)[rle(rev(x))$values==1]+1)
stopIndex<-cumsum(rle(x)$lengths)[rle(x)$values==1]
startIndx试试这个:
y = rle(x)
stopIndex = with(y, cumsum(lengths)[values==1])
startIndex = stopIndex - with(y, lengths[values==1]) + 1
#> stopIndex
#[1] 2 5 9
#> startIndex
#[1] 1 5 7
这个怎么样?[根据alexis_laz的建议编辑的版本]
library(cgwtools)
res <- seqle(which(as.logical(x)))
rbind(res$values, res$values + res$lengths - 1)
[,1] [,2] [,3]
[1,] 1 5 7
[2,] 2 5 9
库(cgwtools)
res优雅的方式是
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
y假设向量由0和1个值组成:
which(diff(c(0L, x)) == 1L)
#[1] 1 5 7
which(diff(c(x, 0L)) == -1L)
#[1] 2 5 9
否则,您将需要类似于x正在查看哪个;)杰出的除非我遗漏了什么,否则您可以将最后一行替换为rbind(res$values,res$values+res$length-1)
谢谢您的建议,现在更容易阅读/理解:)