Determine if all values ​​are contiguous integers in R

I am trying to check if all values ​​in an object (if ordered) are contiguous integer values. For example:

x <- c(1,2,3)
is.adjacent(x)
TRUE

y <- c(1,2,4)
is.adjacent(y)
FALSE

z <- c(4,2,1,3)
is.adjacent(z)
TRUE

      

Any thoughts on a good approach?

+3


source to share


1 answer


Here is the solution. I have constructed it so that it returns TRUE

for a vector that contains a set of consecutive integers, even if some of them are repeated (for example c(1,3,2,1,1,1)

). If you want it to return FALSE

in such cases, just remove the part that calls unique()

.



is.adjacent <- function(X) {
    all(diff(sort(unique(X))) == 1)
}

# Try it out
x <- c(1,2,3)
y <- c(1,2,4)
z <- c(4,2,1,3)

is.adjacent(x)
is.adjacent(y)
is.adjacent(z)

      

+7


source







All Articles