Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I have a SpatialPolygonsDataFrame object. Is there way to use apply on this object rather than using a for loop to iterate features in this object?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

You probably want to iterate over the polygons.

As an example, start with this grid taken from the manual page (but cut down in size):

library(sp)
grd <- GridTopology(c(1,1), c(1,1), c(3,3))
polys <- as.SpatialPolygons.GridTopology(grd)
centroids <- getSpPPolygonsLabptSlots(polys)
x <- centroids[,1]
y <- centroids[,2]
z <- 1.4 + 0.1*x + 0.2*y + 0.002*x*x
data <- SpatialPolygonsDataFrame(polys, 
             data=data.frame(x=x, y=y, z=z, row.names=getSpPPolygonsIDSlots(polys)))

Here sapply is used to create a vector of the polygon identifiers and print it out:

(ids <- sapply(data@polygons, function(p) p@ID))
share|improve this answer
    
Thank you very much! I think this method will greatly accelerate my codes! –  Seen Oct 8 '12 at 20:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.