JadaLovelace
JadaLovelace

Reputation: 204

R sequence format from raw sequence to shortened code

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)?

Upvotes: 2

Views: 57

Answers (3)

akrun
akrun

Reputation: 887771

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)

Upvotes: 1

Kate Ham
Kate Ham

Reputation: 163

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

Upvotes: 0

tmfmnk
tmfmnk

Reputation: 40171

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"

Upvotes: 1

Related Questions