You want to group elements into blocks of consecutive integers. diff can tell you if two consecutive elements are in the same block, cumsum can indicate blocks and tapply can extract the first and last element of each block.
x <- c(1:50, 53, 89:120) y <- tapply( x, c(0,cumsum(diff(x) != 1)), range ) # Format the result y <- sapply(y, function(u) if(u[1]==u[2]) u[1] else paste(u,collapse=":") ) paste(y, collapse=", ")
source share