Collapse continuous integer runs to strings of ranges

后端 未结 6 601
小鲜肉
小鲜肉 2020-11-30 13:50

I have some data in a list that I need to look for continuous runs of integers (My brain thinkrle but don\'t know how to use it here).

It\'s easier to l

6条回答
  •  攒了一身酷
    2020-11-30 14:12

    I think diff is the solution. You might need some additional fiddling to deal with the singletons, but:

    lapply(z, function(x) {
      diffs <- c(1, diff(x))
      start_indexes <- c(1, which(diffs > 1))
      end_indexes <- c(start_indexes - 1, length(x))
      coloned <- paste(x[start_indexes], x[end_indexes], sep=":")
      paste0(coloned, collapse=", ")
    })
    
    $greg
    [1] "7:11, 20:24, 30:33, 49:49"
    
    $researcher
    [1] "42:48"
    
    $sally
    [1] "25:29, 37:41"
    
    $sam
    [1] "1:6, 16:19, 34:36"
    
    $teacher
    [1] "12:15"
    

提交回复
热议问题