R sequence format from raw sequence to shortened code

Viewed 33

In R i can write a sequence of 1 - 9 like 1:9 and it will output c(1,2,3,4,5,6,7,8,9).

I want to do the reverse. If i have a sequence of c(1,2,3,4,5,6,7,8,9) is there any way to get 1:9 as an output? Preferably in a dynamic way, so that for example c(1,2,3,4,6,7,8,9) becomes c(1:4, 6:9)?

3 Answers

One option could be:

sapply(split(x, cumsum(c(1, diff(x)) > 1)), function(x) paste(range(x), collapse = ":"))

    0     1 
"1:4" "6:9"

We can use tapply

tapply(x, cumsum(c(TRUE, diff(x) > 1)), FUN = 
         function(x) paste(min(x), max(x), sep=":"))
 #   1     2 
 #"1:4" "6:9" 

data

x <- c(1,2,3,4,6,7,8,9)

Perhaps a roundabout way, but you can use the head and tail functions to get the first and last item of the vector.

> x <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)
> tail(x, n=1)
[1] 9
> head(x, n=1)
[1] 1
> head(x, n=1):tail(x, n=1)
[1] 1 2 3 4 5 6 7 8 9
Related