2

I've been struggling to find a solution to find the area of overlap between two curves. I'm not dealing with probability density functions with known parameters but curves obtained from smoothing of empirical data points.

The only hint I found is to calculate the area that is not over-lapping as in this code (from here):

x <- seq(-6,6,by = 0.01)
y1 <- dnorm(x,0,1)
y2 <- pnorm(x,1,1.1)
f1 <- approxfun(x, y1-y2)
f2 <- function(z) abs(f1(z))
dif <- integrate(f2, min(x), max(x))

plot(x,y1,type="l",ylim=c(0,1))
lines(x,y2,type="l",col="red")
polygon(c(x,rev(x)),c(y1,rev(y2)), col="skyblue")

enter image description here

This is essentially the area between curves, but what I need is not the highlighted blue area but the white area in-between. So the area of overlap.

I was reading that one has to find the intersections of the two curves on a mathematician's blog but I cannot find how to do this in R either.

Hopefully, someone can help me out.

Any suggestions are helpful. I apologise in advance though, I'm not an expert in maths.

jay.sf
  • 60,139
  • 8
  • 53
  • 110
neko
  • 48
  • 6
  • 2
    a suggestion: you can use `uniroot` to find the intersection. then use 2 integrations to find the white area – chinsoon12 Mar 04 '20 at 00:37

2 Answers2

2

This is the integral of the minimum:

x <- seq(-6,6,by = 0.01)
y1 <- dnorm(x,0,1)
y2 <- pnorm(x,1,1.1)
f <- approxfun(x, pmin(y1,y2))
integrate(f, min(x), max(x))
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
  • Great! Can you help me understand the function? So, what I've understood from the `pmin()` help file is that it's finding the lower value for each position along the x-axis between two vectors. Does it mean if I use `pmax()` I would essentially calculate the same area that I was calculating before (area between curves)? – neko Mar 04 '20 at 14:47
  • 1
    @neko No, with `pmax` you would find the blue area plus the white area of the overlap. – Stéphane Laurent Mar 04 '20 at 14:55
  • Oh yes, that makes sense. I just tried it out and it turns out exactly as you say. Thank you! – neko Mar 04 '20 at 14:56
0

Just do

z <- c(y2[y2 < y1], y1[y1 < y2])
polygon(x, z, col="skyblue")

.

enter image description here

jay.sf
  • 60,139
  • 8
  • 53
  • 110