Check whether vector in R is sequential?

2019-06-27 12:34发布

问题:

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

回答1:

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


回答2:

So, @Iselzer has a fine answer. There are still some corner cases though: rounding errors and starting value. Here's a version that allows rounding errors but checks that the first value is (almost) an integer.

is.sequential <- function(x, eps=1e-8) {
  if (length(x) && isTRUE(abs(x[1] - floor(x[1])) < eps)) {
     all(abs(diff(x)-1) < eps)
  } else {
    FALSE
  }
}

is.sequential(2:5) # TRUE

is.sequential(5:2) # FALSE

# Handle rounding errors?
x <- ((1:10)^0.5)^2
is.sequential(x) # TRUE

# Does the sequence need to start on an integer?
x <- c(1.5, 2.5, 3.5, 4.5)
is.sequential(x) # FALSE

# Is an empty vector a sequence?
is.sequential(numeric(0)) # FALSE

# What about NAs?
is.sequential(c(NA, 1)) # FALSE


标签: r sequence