[R-sig-Geo] Subsetting a spatial polygon dataframe with a for loop

Andrew Niccolai andrew.niccolai at yale.edu
Wed Feb 14 17:31:49 CET 2007


Hi.  I had such great success last time, I thought I would ask for more
assistance.  I have an object (cb.poly) of class "SpatialPolygonsDataFrame".
I would like to subset this object using a for loop that essentially loops
through polygon ID from a larger list.  The code looks like this:

class(cb.poly)
sub.cb.poly <- cb.poly[cb.poly$Plg_id == thresh.poly.id[[687]][1,],]
polygons(sub.cb.poly)
dissolveset <- thresh.poly.id[[687]]
ilength <- nrow(dissolveset)
for (i in 2:ilength){
i <- cb.poly[cb.poly$Plg_id == thresh.poly.id[[687]][i,],]
polygons(i)
sub.cb.poly <- c(sub.cb.poly, i)
}
gg <- SpatialPolygons(sub.cb.poly,pO=1:length(sub.cb.poly))

The object thresh.poly.id[[]] is a "list" class object that holds the unique
polygon names that overlapped with my tree crown polygon (thanks Roger and
Greg and others).

The first time I call sub.cb.poly it is a "SpatialPolygonsDataFrame" class.
I then try to convert to a polygon so that after I loop it through my list
of appropriate polygon IDs I can reconvert to a "SpatialPolygonsDataFrame"
class.  I am attempting this because after the for loop, my sub.cb.poly
object is a "list" class.  I could not determine how to join elements from a
loop into a "SpatialPolygonsDataFrame" class, so I thought I might convert
to polygons and then use SpatialPolygons function (see gg object).  

This is not working for me.  

Ultimately, I want to create an object that is a subset of my original
cb.poly object so that I can do a "unionSpatialPolygons" operation to create
a merged or dissolved object. 

Thanks for any assistance. 


Andrew Niccolai
Doctoral Candidate
Yale School of Forestry
203-432-5144




More information about the R-sig-Geo mailing list