loop through polygons for point in polygon function
On Wed, 16 Mar 2011, david depew wrote:
Dear list, I'd like to loop through all polygons in a shapefile, and count
the # of points of interest in each polygon. I see previous postings suggest
a for loop should work, but I'm not able to extract the individual polygons.
I post the following portion since I can get to this point in my
script....but the extraction step fails (most likely due to my inability to
specify what part of the SpatialPolygonsDataFrame to extract.....
library(sp)
library(maptools)
library(splancs)
library(rgdal)
library(spdep)
nc.sids <- readShapePoly(system.file("etc/shapes/sids.shp",
package="spdep")[1],
ID="FIPSNO", proj4string=CRS("+proj=longlat +ellps=clrk66"))
rn <- sapply(slot(nc.sids, "polygons"), function(x) slot(x, "ID"))
for (i in 1:length(rn)) {
temp.poly= ---- effectively, rn[i], i.e. a polygon with ID=="i". I can then
assign data from the result of the pip function, but I'm having difficulty
extracting each polygon sequentially to do this.
Why do you need to extract the polygons? pts <- spsample(nc.sids, n=5000, type="random") plot(nc.sids, axes=TRUE) points(pts, pch=".") out <- over(xx, pts) where out is a vector with a count for each Polygons object in nc.sids. You will have more work to do if you need to count in each Polygon object within each Polygons object, but that would imply that the input data need reorganising. Hope this helps, Roger
Any help is much appreciated! Thanks!
Roger Bivand Economic Geography Section, Department of Economics, Norwegian School of Economics and Business Administration, Helleveien 30, N-5045 Bergen, Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43 e-mail: Roger.Bivand at nhh.no