Search code examples
roverlapping

how to use 'overlaps' function for multiple intervals?


I try to understand, my dataset whether overlapping (or intersecting) with each other. Let me explain with my example below df1 and df2, start column means, the interval of the row starts on that point, stop means interval end on that point. I try to understand each row has intersected with each other or not, if anyone does not intersect, output will be FALSE. So, there is 'overlaps' ( from the DescTools package) function in R, but it doesn't support checking the multiple overlapping regions. You can see the df1 dataset in which all the rows are intersecting with each other, on the other hand, df2 don't fit this rule, since row 5 is not intersecting with row 2 or row 4, my expected output is TRUE FALSE, for the example; df1's output TRUE, and df2's output is FALSE. Thanks.

df1<-data.frame(start=c(100,90,130,110), stop=c(200,140,270,150))

df2<-data.frame(start=c(100,90,130,110, 170), stop=c(200,140,270,150,190))

edit1:

 library(DescTools)

(1,3) %overlaps% (2,5), I try to do this for each row of my dataset, I mean each row compared with other rows with %overlaps%.

edit2: My solution is: for df1

 x<-combinations(nrow(df1),2)
    
    TF <- NULL
    for (ill in 1:nrow(x)) {TF[ill]<- df[x[ill,1],] %overlaps% df[x[ill,2],]  }
    T<-all(TF)

Solution

  • I'm not sure, that I correctly got your question. But might you look for something like

    library(DescTools)
     
    all(apply(df1, 1, function(x) all(apply(df1, 1, `%overlaps%`, x))))
    # [1] TRUE
    
    all(apply(df2, 1, function(x) all(apply(df2, 1, `%overlaps%`, x))))
    # [1] FALSE
    

    ?