rintersectioncdfecdf

How can I get the intersection point of two crossing ecdfs in R?


I have two ecdf plots using below code:

ecdf1 <- ecdf(data1)
ecdf2 <- ecdf(data2)

These plots are crossing each other. I need to take the crossing point (intersection point) coordinates. How should I do this in R?


Solution

  • Lets' create a reproducible example to demonstrate:

    set.seed(1)
    
    data1 <- rnorm(50) + 1.2
    data2 <- rexp(50)
    

    Now we use your code to create the two ecdf functions:

    ecdf1 <- ecdf(data1)
    ecdf2 <- ecdf(data2)
    

    If we plot them, we will see these curves intersect at two points: once between 0 and 1, and again just above 2.

    plot(ecdf1, col = "red")
    plot(ecdf2, col = "blue", add = TRUE)
    

    enter image description here

    To find these exact points, we create a function of x that is the difference between the two ecdf functions at x. We then use the function uniroot to determine where this difference function is equal to 0:

    diff_func <- function(x) ecdf1(x) - ecdf2(x)
    
    root1 <- uniroot(diff_func, c(0, 1))$root # Finds the lower intersection
    root2 <- uniroot(diff_func, c(2, 3))$root # Finds the upper intersection
    

    We can check our results make sense:

    root1
    #> [1] 0.1568627
    root2
    #> [1] 2.055556
    

    And even plot segments to demonstrate the intersections are correct:

    segments(root1, y0 = 0, y1 = ecdf1(root1), lty = 2)
    segments(root2, y0 = 0, y1 = ecdf1(root2), lty = 2)
    

    enter image description here

    Created on 2023-02-26 with reprex v2.0.2