rr-sfr-sp

Check if lat/lon in polygon (R)


I have a lat/lon combination and want to check whether the point is inside a polygon (sp::Polygon class)

Consider this example:

UKJ32 <- sp::Polygon(cbind(c(-1.477037449999955, -1.366895449999959, -1.365159449999965, -1.477037449999955),
                           c(50.923958250000027, 50.94686525000003, 50.880069750000018, 50.923958250000027))) %>%
   list() %>% 
   sp::Polygons(ID="UKJ32 - Southampton")

I would now like to test whether the points in df are in this polygon (and if so, return the Polygon ID).

tibble(lon = c(-1.4, 10), lat = c(50.9, 10))

Can someone tell me how I get to the result

tibble(lon = c(-1.4, 10), lat = c(50.9, 10), polyg_ID = 'UKJ32')

Solution

  • If you wish to stick to sp, there is a point.in.polygon() function in sp package:

    UKJ32 <- sp::Polygon(cbind(c(-1.477037449999955, -1.366895449999959, -1.365159449999965, -1.477037449999955),
                               c(50.923958250000027, 50.94686525000003, 50.880069750000018, 50.923958250000027))) |>
      list() |>
      sp::Polygons(ID="UKJ32 - Southampton")
    
    a <- tibble::tibble(lon = c(-1.4, 10), lat = c(50.9, 10))
    
    sp::point.in.polygon(a$lon, a$lat, UKJ32@Polygons[[1]]@coords[,1], UKJ32@Polygons[[1]]@coords[,2])
    #> [1] 1 0
    

    Created on 2022-10-16 with reprex v2.0.2