Collapse rows with overlapping ranges

前端 未结 3 2128
遇见更好的自我
遇见更好的自我 2020-11-30 09:35

I have a data.frame with start and end time:

ranges<- data.frame(start = c(65.72000,65.72187, 65.94312,73.75625,89.61625),stop = c(79.72187,79.72375,79.9         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 09:59

    Here is a data.table solution

    library(data.table)
    setDT(ranges)
    ranges[, .(start=min(start), stop=max(stop)),
           by=.(group=cumsum(c(1, tail(start, -1) > head(stop, -1))))]
       group    start      stop
    1:     1 65.72000  87.75625
    2:     2 89.61625 104.94062
    

    Here, groups are constructed by checking if the previous start is greater than stop and then using cumsum. within each group, minimum of start and maximum of stop are calculated.

提交回复
热议问题