You will want to import your shape file. You can try package rgdal
, specifically function readOGR
.
After reading into R your csv file, you may want to coerce it to a SpatialPoints
class. Make sure your projections are identical.
After you have the polygon and SpatialPoints
, it should be just a matter of using function over
from package sp
.
I recently asked a similar question. I hope the data in the self contained example should be sufficient to work through the second part of your question.
Let's set up some sample data:
library(sp)
library(spdep)
example(columbus)
plot(columbus)
We'll now get some points. Click 20 times on the map, some inside and some outside polygons:
pts = locator(20,type="p")
Convert to Spatial data type:
spts = SpatialPoints(pts)
Now use rgeos
to compute point-polygon distances, and take the minimum for each point:
library(rgeos)
> apply(gDistance(spts, columbus,byid=TRUE),2,min)
1 2 3 4 5 6 7
0.25947439 0.03898401 1.27156515 1.50490316 0.00000000 0.00000000 0.00000000
8 9 10 11 12 13 14
0.00000000 0.00000000 0.31312329 0.26742466 0.53934325 0.07764322 0.03909773
15 16 17 18 19 20
0.11156343 0.29243322 0.08872334 0.00000000 0.00000000 0.00000000
There you go. That's the minimum distance from each of the 20 points to any of the polygons. The zeroes are for points inside one of the polygons.
Note you should use data in a projected spatial coordinate system and not lat-long.
If you have 17,000 points then you might want to do this in smaller subsets to avoid creating a 17,000 x 5,000 matrix if you have 5,000 polygons. You didn't say.
Best Answer
Think of the over function returning a query, now you have to do something with it. One easy approach is to pass an is.na() evaluation to a bracket index of the the SpatialPolygonsDataFrame object. This will return a subset of polygons that do not intersect the points.
First, create some example data.
Now, we can subset the polygons to ones not intersecting points.
By adding a "is not" evaluation (using !), you can invert the subset to include polygons that DO intersect the points.