1

I have a shapefile and I would like to find the polygon containing a list of points. For example,

rio <- readShapeSpatial("setores_rio.shp")  
bairrorio.fort<- fortify(rio , region = "neighborhood")

head(bairrorio.fort)
   long       lat order  hole piece          group           id
1 -43.17769 -22.91814     1 FALSE     1 330455705001.1 330455705001
2 -43.17771 -22.91814     2 FALSE     1 330455705001.1 330455705001
3 -43.17771 -22.91808     3 FALSE     1 330455705001.1 330455705001
4 -43.17793 -22.91811     4 FALSE     1 330455705001.1 330455705001
5 -43.17811 -22.91768     5 FALSE     1 330455705001.1 330455705001
6 -43.17802 -22.91766     6 FALSE     1 330455705001.1 330455705001

Assume that p = c(long, lat) is a point with lat long localization. I would like to find the id(neighborhood) (see bairrorio.fort) containing the point p.

MAOC
  • 625
  • 2
  • 8
  • 26
  • `bairrorio.fort[bairrorio.fort$long==long & bairrorio.fort$lat==lat,"id"]` will give what you want – user227710 May 27 '15 at 21:49
  • 2
    check out `over()` in the sp package. – cory May 27 '15 at 22:00
  • Are you sure that the point p= c(long, lat) can be any point? It isn't working... I think that your suggestion may works only for point in bairrorio.fort, nevertheless, when I run with p = c(-43.17769 -22.91814)(see the first row of bairrorio.fort) the result is > bairrorio.fort[bairrorio.fort$long == -43.17769 & bairrorio.fort$lat == -22.91814, "id"] character(0) – MAOC May 27 '15 at 22:03
  • 1
    Don't use `readShapeSpatial` to read shapefile. Use `readOGR` from `rgdal` package. –  May 28 '15 at 02:03

1 Answers1

1

You can use point.in.polygon from sp:

library(sp)
library(magrittr)

bairrorio.fort %>% 
  split(.$id) %>% 
  sapply(function(x) point.in.polygon(p[1], p[2], x$long, x$lat) > 0) %>%  
  names(.)[.]
bergant
  • 7,122
  • 1
  • 20
  • 24