Home > Mobile >  Select points in a polygon
Select points in a polygon

Time:03-16

I’m getting angry about something that seems simple to me. I would like to select the points inside a polygon with the sf package. Both have the same CRS : EPSG:27572 "NTF (Paris) / Lambert zone II. I can't provide a reproductible example because data are confidential...

My points :

    Classes ‘sf’ and 'data.frame':  5033 obs. of  6 variables:
     $ date    : chr  "18/04/2014" "17/04/2014" "21/04/2014" "22/04/2014" ...
     $ id      : chr  "Auberta" "Auberta" "Auberta" "Auberta" ...
     $ sex     : chr  "F" "F" "F" "F" ...
     $ age     : chr  "0" "0" "0" "0" ...
     $ year    : chr  "2014" "2014" "2014" "2014" ...
     $ geometry:sfc_POINT of length 5033; first list element:  'XY' num  472270 1752852
     - attr(*, "sf_column")= chr "geometry"
     - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA NA NA NA
      ..- attr(*, "names")= chr [1:5] "date" "id" "sex" "age" ...

My polygon :

    Classes ‘sf’ and 'data.frame':  1 obs. of  2 variables:
     $ zone2   : chr "30T"
     $ geometry:sfc_POLYGON of length 1; first list element: List of 1
      ..$ : num [1:29, 1:2] 425644 422338 419034 415729 412423 ...
      ..- attr(*, "class")= chr [1:3] "XY" "POLYGON" "sfg"
     - attr(*, "sf_column")= chr "geometry"
     - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA
      ..- attr(*, "names")= chr "zone2"

I tried the st_join function but no matter what I put in the join argument, all points are subset. I attach a screenshot.

View of the polygon and the points

HELP PLEASE !

CodePudding user response:

I show here how to select the points inside a given polygon, Basically I filtered the initial points selecting only included on the box (the final result is in point_in_pol):

library(mapSpain)
library(sf)
library(dplyr)
library(ggplot2)


box <- esp_get_prov("Asturias") %>%
  st_transform(27572) %>%
  st_bbox() %>%
  st_as_sfc()

points <- esp_get_capimun(region = c("Asturias", "Galicia")) %>%
  st_transform(27572)

p <- ggplot(box)  
  geom_sf()  
  geom_sf(data = points)

p


enter image description here


# Point on polygon
# Logical stating if the polint intersect the polygon
logi_point_in_pol <- st_intersects(box, points, sparse = FALSE)

point_in_pol <- points[as.vector(logi_point_in_pol), ]

p  
  geom_sf(data = point_in_pol, color = "red")


enter image description here

  •  Tags:  
  • r sf
  • Related