Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether vector in R is sequential?

Tags:

r

sequence

How can I check whether an integer vector is "sequential", i.e. that the difference between subsequent elements is exactly one. I feel like I am missing something like "is.sequential"

Here's my own function:

is.sequential <- function(x){
    all(diff(x) == rep(1,length(x)-1))
}    
like image 852
Matt Bannert Avatar asked Dec 14 '11 15:12

Matt Bannert


1 Answers

There's no need for rep since 1 will be recicled:

Edited to allow 5:2 as true

is.sequential <- function(x){
  all(abs(diff(x)) == 1)
}  

To allow for diferent sequences

is.sequential <- function(x){
 all(diff(x) == diff(x)[1])
}
like image 118
Luciano Selzer Avatar answered Sep 22 '22 20:09

Luciano Selzer