Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a sequence has "gaps" in R

Tags:

r

sequence

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
like image 838
JasonAizkalns Avatar asked Apr 28 '16 16:04

JasonAizkalns


2 Answers

library(zoo)
is.regular(x3, strict=TRUE)
is.regular(x3, strict=FALSE)
like image 200
Jim Avatar answered Sep 20 '22 10:09

Jim


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))
like image 22
Ian Campbell Avatar answered Sep 22 '22 10:09

Ian Campbell