Suppose I create the following image from 40 (x, y) pairs.

Now, given the extra points in black, I would like to be able to calculate how many points fall into the blue area, and how many fall out into the street (very effective, since I will do this many times inside an expensive cycle). To illustrate what I'm looking for, consider the following figure:

So, as you can see from the above figure, I would like to say that there are 3 black dots outside the blue area and 7 black points inside the blue area.
Here is the code I wrote to execute the above drawings.
#x,y data x = rnorm(40) y = rnorm(40) #Calculates the green points d = data.frame(x,y) D = d[order(d$x,d$y,decreasing=FALSE),] front = D[which(!duplicated(cummin(D$y))),] plot(x,y,pch=21,bg="red",xlim=c(-5,5),ylim=c(-5,5)) points(front$x,front$y,pch=21,bg="green") rect(front$x,front$y,max(x)+100000,max(y)+100000,col="lightblue",border=NA) points(x,y,bg="red",pch=21) points(front$x,front$y,bg="green",pch=21) #Additional 10 black points w = rnorm(10,3) z = rnorm(10,-1) points(w,z,pch=19,col="black")
I can really understand how many points fall in the blue area, however I have to do this calculation inside the loop, which is very slow. I would like to do the calculation outside the loop to speed up my calculations.