I would like to determine if a sequence contains any gaps or irregular steps? Not sure if this is the right way to phrase this and there's a good chance that this is duplicate (but I was unable to find a good question).
The following has_gap
function gives me the correct results, but seems a bit clunky? Perhaps there is something built-in that I haven't discovered?
x1 <- c(1:5, 7:10)
x2 <- 1:10
x3 <- seq(1, 10, by = 2)
x4 <- c(seq(1, 6, by = 2), 6, seq(7, 10, by = 2))
has_gap <- function(vec) length(unique(diff(vec))) != 1
vecs <- list(x1, x2, x3, x4)
sapply(vecs, has_gap)
# [1] TRUE FALSE FALSE TRUE
library(zoo)
is.regular(x3, strict=TRUE)
is.regular(x3, strict=FALSE)
As noted by G. Grothendieck in the comments, one approach is:
has_gaps <- \(x)!!diff(range(diff(x)))
Another approach might be:
has_gaps2 <- \(x)var(diff(x))>0
If performance is an issue, rawr suggested:
has_gaps3 <- \(x)!isTRUE(all.equal(cor(x,seq_along(x)),1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With