I am using point.in.polygon function in sf package to determine whether a set of data fall within a polygon or not. Here is a snippet of the data and polygon visualization enter image description here

As the figure shows, there must be at least one point fully lies in the polygon, however, the point.in.polygon function returns all zero, which means the function thinks all points are exterior to the polygon.

Where am I do wrong?

codes subDist <- point.in.polygon(CD8_Pts[,1], CD8_Pts[,2], sub_current_poly[,1], sub_current_poly[,2])

Edit: The following link is the polygon coordinates. https://livejohnshopkins-my.sharepoint.com/:u:/g/personal/hmi1_jh_edu/EeC-sUzqPZJFtoUzM-r5DQ4B_aIsLri4G29RAi47uO42zw?e=Gw2oHt

  • There;s no such function in sf or spatstat packages. Theres one in sp which I assume works when fed the correct data. So the assumption is that your data isnt i the right format. Without your data there;s no way we can help you.
    – Spacedman
    Aug 24 '19 at 16:46
  • Thank you for the correction. I attached the polygon data to the OneDrive, and you can download using this link mentioned in the question. You can use any data to test the function. (FYI I am sure that point (15, 20) should lie in the polygon
    – HAOYANG Mi
    Aug 25 '19 at 1:15

Your polygon seems to be two copies of the same ring, exactly overlapping. Look at the first five points and then the first five after the half-way mark:

> polygons[1:5,]
           x      y n
288842 4.232 20.240 5
288851 4.232 20.248 5
288861 4.232 20.256 5
288871 4.224 20.264 5
288881 4.224 20.272 5
> polygons[(nrow(polygons)/2)+(1:5),]
           x      y n
288844 4.232 20.240 5
288853 4.232 20.248 5
288863 4.232 20.256 5
288873 4.224 20.264 5
288883 4.224 20.272 5

The point (15,20) isn't in the polygon defined by this double ring:

> point.in.polygon(15,20,polygons[,1], polygons[,2])
[1] 0

But if you take only the first half of your polygon object then it is:

> point.in.polygon(15,20,polygons[1:(nrow(polygons)/2),1], polygons[1:(nrow(polygons)/2),2])
[1] 1

I think this duplication of the ring is messing up the point-in-polygon algorithm which expects a well-defined single ring polygon.

  • Thank you for your answer! Perfectly solved my problem!
    – HAOYANG Mi
    Aug 26 '19 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.