How to create a set of ranges from a vector in R?

234 views Asked by At

Let's say I have a vector of numbers specifying lengths.

x = c(3,5,4,10)

Then I run cumsum to get their ranges.

cumsum(x)

3  8 12 22

How would I pair each up to produce pairs of ranges, starting with 1.

Preferable as a character vector:

c("1-3", "3-8", "8-12", "12-22")
2

There are 2 answers

1
A5C1D2H2I1M1N2O1R2T1 On BEST ANSWER

You could use paste like this:

paste(c(1, cumsum(x))[-(length(x)+1)], cumsum(x), sep = "-")
# [1] "1-3"   "3-8"   "8-12"  "12-22"
0
akrun On

Another option would be to use sprintf

 x1 <- c(1, cumsum(x))
 sprintf('%d-%d', x1[-length(x1)], x1[-1])
 #[1] "1-3"   "3-8"   "8-12"  "12-22"