Extract first continuous sequence in vector

Viewed 975

I have a vector:

as <- c(1,2,3,4,5,9)

I need to extract the first continunous sequence in the vector, starting at index 1, such that the output is the following:

1 2 3 4 5

Is there a smart function for doing this, or do I have to do something not so elegant like this:

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]
}

It does the trick, but I would expect that there is a function that can already do this.

2 Answers
Related