Skip to Content

How to partition a vector into groups of neighbors in R?

I have a vector, such as c(1,3,4,5,9,10,17,29,30) and I would like to group together the elements that form a series in a ragged vector resulting in:

L1: 1

L2: 3,4,5

L3: 9,10

L4: 17

L5: 29,30

Naive code (of an ex-C programmer):

partition.neighbors <- function(v)
{
    result <<- list() #jagged array
    currentList <<- v[1] #current series
 
    for(i in 2:length(v))
    {
        if(v[i] - v [i-1] == 1)
        {
            currentList <<- c(currentList, v[i])
        }
        else
        {
            result <<- c(result, list(currentList))
            currentList <<- v[i] #next series
        }       
    }
 
    return(result)  
}

Now I understand that

a) R is not C (despite the curly brackets)
b) global variables are pure evil
c) that is a horribly inefficient way of achieving the result

, so any better solutions are welcome.