2

I have two object :

pts=readOGR(dsn="overpass-turbo/shp/",layer="amenity")
poly=readOGR(dsn="overpass-turbo/shp/",layer="polygons")

Like

points in polygon

I would have, as a result, a spatial data frame with all points in the polgygon... I'have find something in this post but it doesn't work as I want!

a<-over(pts, poly)

but a in not a Sp data frame !!

I know !! I always have troubles with over fonction ...

Community
  • 1
  • 1
delaye
  • 1,357
  • 27
  • 45

2 Answers2

4

I have find something more :-)

pts_in<-pts[!is.na(over(pts,poly)),]

enter image description here

It keep only points in the polygon (source : http://cran.r-project.org)

delaye
  • 1,357
  • 27
  • 45
  • 1
    not sure if this works. i get an error. Better use this: https://stackoverflow.com/questions/21567028/extracting-points-with-polygon-in-r – joaoal Mar 29 '18 at 09:33
1

Not entirely sure what you exactly want but I assume poly is your spatial data frame of choice. I think you have to do the following if you want to count the number of points in your polygon:

pts_in=over(SpatialPolygons(poly@polygons,SpatialPoints(pts),
                returnlist=TRUE)
poly$npoints<-unlist(lapply(pts_in,length)

If on the other hand you want to assign the corresponding polygon to each point, you do the following:

pts$nrow=over(SpatialPoints(pts),SpatialPolygons(poly@polygons),
          returnlist=TRUE)

You can also check this reference for some useful hints.

horseoftheyear
  • 917
  • 11
  • 23
  • Hi , I have add an image ... I would like to remove all point outside the polygon. – delaye Apr 17 '14 at 11:54
  • So if you use the method where your count the points in the polygons the points outside of the polygons will not be counted. If you use the method where you create the correspondence list (`pts$nrow`) you can simply exclude the points outside the polygon by removing the `NA's` for `pts$nrow` from your data frame. – horseoftheyear Apr 17 '14 at 11:58