How to merge overlapping integer vector elements of a list in R

r

Solution

A naive approach could be this:

l2 <- l1
for(i in seq_along(l2)[-length(l2)]) {
   if(length(intersect(l2[[i]], l2[[i+1]])) > 0) { 
      l2[[i+1]] <- sort.int(unique(c(l2[[i]], l2[[i+1]])))
      l2[[i]] <- as.list(NULL)
   }   
}
dput(Filter(function(x) length(x) > 0, l2))
list(2:3, 4:5, 6:7, 8:9, 15:22, 23:25, 26:27, 30:32, 33:34, 35:36, 
    38:39, 42:43, 44:45, 46:47, 50:51, 54:56, 57:58, 59:60, 64:65, 
    66:67, 68:70, 73:74, 77:78, 80:81, 82:83, 84:85, 88:89, 90:91, 
    92:93, 94:95, 96:97, 100:101, 103:104, 105:106, 107:108)

Problem

I have a list of vectors: ``` l1 <- list(2:3, 4:5, 6:7, 8:9, 16:19, 15:19, 18:20, 20:21, 21:22, 23:24, 23:25, 26:27, 30:31, 31:32, 33:34, 35:36, 38:39, 42:43, 44:45, 46:47, 50:51, 54:55, 55:56, 57:58, 59:60, 64:65, 66:67, 68:69, 69:70, 73:74, 77:78, 80:81, 82:83, 84:85, 88:89, 90:91, 92:93, 94:95, 96:97, 100:101, 103:104, 105:106, 107:108) ``` Where there are vectors that overlap with eachother (inclusive), I need them to be merged (so reducing the length of the list) so that the widest range possible is covered. For e.g. taking the first 7 elements of `l1`, `l1 <- list(2:3, 4:5, 6:7, 8:9, 16:19, 15:19, 18:20,...` I want this transformed into: `l2 <- list(2:3, 4:5, 6:7, 8:9, 15:20,...` How can I do this efficiently?

Original source