5

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?

7

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))
1
  • Thank you very much! I think this method will greatly accelerate my codes! – Seen Oct 8 '12 at 20:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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