Collapse consecutive runs of numbers to a string of ranges

前端 未结 3 1302
无人及你
无人及你 2020-12-15 05:57

Let\'s say I have the following vector of numbers:

vec = c(1, 2, 3, 5, 7, 8, 9, 10, 11, 12)

I\'m looking for a function that will create a

3条回答
  •  爱一瞬间的悲伤
    2020-12-15 06:28

    Adding another alternative, you could use a deparseing approach. For example:

    deparse(c(1L, 2L, 3L))
    #[1] "1:3"
    

    Taking advantage of as.character "deparse"ing a given "list" as input, we could use:

    as.character(split(as.integer(vec), cumsum(c(TRUE, diff(vec) != 1))))
    #[1] "1:3"  "5"    "7:12"
    toString(gsub(":", "-", .Last.value))
    #[1] "1-3, 5, 7-12"
    

提交回复
热议问题