Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 7 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):

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


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.