JasonAizkalns
JasonAizkalns

Reputation: 20463

Determine if a sequence has "gaps" in R

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

Upvotes: 8

Views: 1647

Answers (2)

Ian Campbell
Ian Campbell

Reputation: 24820

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

Upvotes: 1

Jim
Jim

Reputation: 191

library(zoo)
is.regular(x3, strict=TRUE)
is.regular(x3, strict=FALSE)

Upvotes: 1

Related Questions