# Non-Consecutive Intervals

This code gives me the consecutive intervals. What do I have to change to give me the NON consecutive intervals? Example:

``````# Función para encontrar los intervalos en los que no hay consecutividad en una lista numérica
intervalos_consecutivos <- function(vector) {
cambios <- c(0, which(diff(vector) != 1), length(vector))
intervalos <- lapply(1:(length(cambios)-1), function(i) {
if(cambios[i+1] - cambios[i] > 1) {
return(vector[c(cambios[i]+1, cambios[i+1])])
} else {
return(vector[c(cambios[i]+1)])
}
})
return(intervalos)
}

# Ejemplo de uso
vector_ejemplo <- c(1, 2, 3, 5, 6, 8, 9, 10)

``````

CONSOLE:

``````[[1]]
[1] 1 3

[[2]]
[1] 5 6

[[3]]
[1]  8 10
``````

I want:

``````[[1]]
[1] 3 5

[[2]]
[1] 6 8
``````

Where is no number between them.

Well, Dear Community, solved my own problem. For whoever wants to know:
Let's say this vector: c(1,5,6,8,9,10,23,47,48) and I want this result: (1,5),(6,8),(10,23) y (23,47). Code this:

``````# Vector de ejemplo
vector <- c(1, 5, 6, 8, 9, 10, 23, 47, 48)

# Función para encontrar intervalos donde no hay números consecutivos
encontrar_intervalos <- function(vector) {
intervalos <- list()
i <- 1

while (i < length(vector)) {
if (vector[i+1] - vector[i] > 1) {
intervalo <- c(vector[i], vector[i+1])
intervalos <- c(intervalos, list(intervalo))
}
i <- i + 1
}

return(intervalos)
}

# Llamar a la función y mostrar los intervalos
intervalos <- encontrar_intervalos(vector)
print(intervalos)

``````

Greetings from Spain. See u!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.