views:

56

answers:

1

Hi,

I am working with shapefiles in R, one is point.shp the other is a polygon.shp. Now, I would like to intersect the points with the polygon, meaning that all the values from the polygon should be attached to the table of the point.shp.

I tried overlay() and spRbind in package sp, but nothing did what I expected them to do.

Could anyone give me a hint?

Thank you! Jens

+2  A: 

If you do overlay(pts,polys) where pts is a SpatialPointsDataFrame object and polys is a SpatialPolygonsDataFrame object then you get back a vector the same length as the points giving the row of the polygons data frame. So all you then need to do to combine the polygon data onto the points data frame is:

 o = overlay(pts,polys)
 pts@data = cbind(pts@data,polys[o,])

HOWEVER! If any of your points fall outside all your polygons, then overlay returns an NA, which will cause polys[o,] to fail, so either make sure all your points are inside polygons or you'll have to think of another way to assign values for points outside the polygon...

Spacedman
Thank you ! Somehow I overlooked the second line! Works perfectly well. but, I will post another question in a second: what to do if one wants to attach a simple data.frame to a spatialpolygondataframe?
Jens