R 提取向量中的第一个连续序列

R 提取向量中的第一个连续序列,r,indexing,continuous,R,Indexing,Continuous,我有一个向量: as <- c(1,2,3,4,5,9) 有没有一个智能的功能可以实现这一点,或者我必须做一些不那么优雅的事情: a <- c(1,2,3,4,5,9) is_continunous <- c() for (i in 1:length(a)) { if(a[i+1] - a[i] == 1) { is_continunous <- c(is_continunous, i) } else { break } } continu

我有一个向量:

as <- c(1,2,3,4,5,9)
有没有一个智能的功能可以实现这一点,或者我必须做一些不那么优雅的事情:

a <- c(1,2,3,4,5,9)
is_continunous <- c()
for (i in 1:length(a)) {
  if(a[i+1] - a[i] == 1) {
    is_continunous <- c(is_continunous, i)
  } else {
    break
  }
}

continunous_numbers <- c()
if(is_continunous[1] == 1) {
  is_continunous <- c(is_continunous, length(is_continunous)+1)
  continunous_numbers <- a[is_continunous]
}

a如果连续序列的索引仅从索引1或第一个序列开始,则不清楚您需要什么,无论起始索引是什么

在这两种情况下,都需要先检查相邻图元之间的差异:

d_as <- diff(as)
rle
允许知道相同值的每个连续序列的长度和值

如果需要第一个连续序列,无论起始索引是什么:


rle_d_as捕获序列的一个简单方法是找到向量的
diff
,并获取
diff==1的所有元素加上下一个元素,即

d1<- which(diff(as) == 1)
as[c(d1, d1[length(d1)]+1)]

d1@Sotos如果输入
为@zx8754是的……似乎太简单了:)可能类似
d1@Sotos也许是作为答案发布,但我觉得这是一个骗局。@Cath这就是为什么我没有作为答案发布。我想既然OP澄清了,那么我应该回答它…?谢谢你的全面回答。@EsbenEickhardt不客气,我很高兴它有帮助:-)谢谢你的回答。我不是想偷你的答案,但我只是想让人们知道我得到了一个令人满意的答案,我的问题得到了回答。@EsbenEickhardt不用担心。你做得很好。我知道你的意思很好:)@EsbenEickhardt做了一个在任何情况下都能工作的函数很酷,谢谢!“我相信这在其他情况下会派上用场。”埃斯贝尼克哈特只是想澄清一下。您需要返回连续值的索引,而不是值本身,对吗?(您的示例不清楚,因为在索引1、2、3、4、5处有值1、2、3、4、5):)
if(d_as[1]==1) 1:(rle(d_as)$lengths[1]+1) else NULL
# [1] 1 2 3 4 5
rle_d_as <- rle(d_as)
which(d_as==1)[1]+(0:(rle_d_as$lengths[rle_d_as$values==1][1]))
as <- c(1,2,3,4,5,9) 
d_as <- diff(as)
rle_d_as <- rle(d_as)
which(d_as==1)[1]+(0:(rle_d_as$lengths[rle_d_as$values==1][1]))
#[1] 1 2 3 4 5

as <- c(4,3,1,2,3,4,5,9)
d_as <- diff(as)
rle_d_as <- rle(d_as)
which(d_as==1)[1]+(0:(rle_d_as$lengths[rle_d_as$values==1][1]))
# [1] 3 4 5 6 7

as <- c(1, 2, 3, 6, 7, 8)
d_as <- diff(as)
rle_d_as <- rle(d_as)
which(d_as==1)[1]+(0:(rle_d_as$lengths[rle_d_as$values==1][1]))
# [1] 1 2 3
d1<- which(diff(as) == 1)
as[c(d1, d1[length(d1)]+1)]
get_seq <- function(vec){
  d1 <-  which(diff(as) == 1)
  if(all(diff(d1) == 1)){
    return(c(d1, d1[length(d1)]+1))
  }else{
    d2 <- split(d1, cumsum(c(1, diff(d1) != 1)))[[1]]
    return(c(d2, d2[length(d2)]+1))
  }
}


#testing it

as <- c(3, 5, 1, 2, 3, 4, 9, 7, 5, 4, 5, 6, 7, 8)
get_seq(as)
#[1] 3 4 5 6

as <- c(8, 9, 10, 11, 1, 2, 3, 4, 7, 8, 9, 10)
get_seq(as)
#[1]  1 2 3 4

as <- c(1, 2, 3, 4, 5, 6, 11)
get_seq(as)
#[1] 1 2 3 4 5 6