在载体中提取第一个连续序列

Esb*_*rdt 3 indexing r continuous

我有一个矢量:

as <- c(1,2,3,4,5,9)
Run Code Online (Sandbox Code Playgroud)

我需要从索引1开始提取向量中的第一个连续序列,以便输出如下:

1 2 3 4 5
Run Code Online (Sandbox Code Playgroud)

这样做是否有智能功能,或者我必须做一些不那么优雅的事情:

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]
}
Run Code Online (Sandbox Code Playgroud)

它可以解决问题,但我希望有一个功能可以做到这一点.

Cat*_*ath 5

如果连续序列的索引只是从索引1或第一个序列开始,无论起始索引是什么,都不清楚你需要什么.

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

d_as <- diff(as)
Run Code Online (Sandbox Code Playgroud)

如果只在从索引1开始时需要第一个序列:

if(d_as[1]==1) 1:(rle(d_as)$lengths[1]+1) else NULL
# [1] 1 2 3 4 5
Run Code Online (Sandbox Code Playgroud)

rle 允许知道每个相同值的连续序列的长度和值.

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

rle_d_as <- rle(d_as)
which(d_as==1)[1]+(0:(rle_d_as$lengths[rle_d_as$values==1][1]))
Run Code Online (Sandbox Code Playgroud)

示例(第二个选项):

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
Run Code Online (Sandbox Code Playgroud)