I've studied this question and created my own 4-contour map based on several thousands of pairs of longitude and latitude points, but I'm not getting the correct number of points inside each of the 4 contours using the points.in.polygon method mentioned in the above question.
Here is the code so far using MASS library:
# use kde2d function to create kernel density estimates
x <- pedestrian.df$longitude
y <- pedestrian.df$latitude
dens <- kde2d(x, y, n=200)
# create the contours to plot - 70%, 50%, 25%, 10% of density contained in each contour
prob <- c(0.7, 0.5, 0.25, 0.1)
dx <- diff(dens$x[1:4])
dy <- diff(dens$y[1:4])
sz <- sort(dens$z)
c1 <- cumsum(sz) * dx * dy
levels <- sapply(prob, function(x) {
approx(c1, sz, xout = 1 - x)$y
})
#create the contour plot using smoothScatter which smooths the collisions into kernel densities
smoothScatter(x,y) + contour(dens, levels=levels, labels=prob, col = c("green", "yellow", "orange", "red"), lwd = 1.5, add=T)
This correctly generates the what I expected:
I then tried to use the points.in.polygon function from sp library as in the answer to the above linked question:
ls <- contourLines(dens, level=levels)
zone_1 <- point.in.polygon(df$longitude, df$latitude, ls[[4]]$x, ls[[4]]$y)
zone_2 <- point.in.polygon(df$longitude, df$latitude, ls[[3]]$x, ls[[3]]$y)
zone_3 <- point.in.polygon(df$longitude, df$latitude, ls[[2]]$x, ls[[2]]$y)
zone_4 <- point.in.polygon(df$longitude, df$latitude, ls[[1]]$x, ls[[1]]$y)
But this results in incorrect number of points per zone or contour. I know this is not right because each contour should have progressively more points as the contour gets larger.
I tried looking at ls (a list that stores a list of all the x and y coordinates of the polygons), but there are 15 levels, not the 4 I intuitively would've thought would be there. There are even multiple levels among the 15 that have the same value. I suspect the answer to my issue lies in subsetting this list of lists correctly to include the 4 levels that correspond to my 4 contours, but ls[[1:7]]$x, ls[[1:7]]$y doesn't work.
Thanks for any help and let me know if I could clarify anything!