Substract ranges between 2 tables in R

Viewed 48

If I have:

df1:

  start end
     1   4
     5   7
     8  12
    20  22 

and

df2:

  start end
     3   6
    10  15

How do I get a table that contains intervals of df1 that are not in df2 in R?

For example, the first row of df1 is (1..4) and since it overlaps with interval (3..6) in df2, I want (1..4) - (3..6) which is (1..2) (i.e. interval in the first row of df1 that is not in df2).

In the end, I want a result like this:

  start end
     1   2
     7   7
     8   9
    20  22
1 Answers

We can create a sequence between df2's start and end and store it in vals. For each row in df1 we can then include range of only those values which are not present in vals.

vals <- unlist(Map(seq, df2$start, df2$end))
t(apply(df1, 1, function(x) range(setdiff(x[1]:x[2], vals))))

#     [,1] [,2]
#[1,]    1    2
#[2,]    7    7
#[3,]    8    9
#[4,]   20   22
Related