I have a line of code that renames the id's of polygons in a SpatialPolygonsDataFrame by directly manipulating the ID slot of the polygon. I'm a bit slow when it comes to sapply, having used for loops for at least 20 years. Anyhow I have a piece of code that works using a for loop, but its really slow. I would like to replace it with a sapply command but can't figure it out. My code looks like this:

for(v in 1:nrow(SPoly)) {
    SPoly@polygons[[v]]@ID <- SPoly@data[v,3]

Can anyone suggest an sapply implementation of same?

1 Answer 1


sapply won't be faster in this case. Try spChFIDs instead (package sp):

SPoly <- spChFIDs(SPoly, as.character(SPoly@data[, 3]))

From ?spChFIDs:

change feature IDs in spatial objects


When the feature IDs need to be changed in SpatialLines* or SpatialPolygons* objects, these methods may be used. The new IDs should be a character vector of unique IDs of the correct length.

  • Works brilliantly - and almost instantaneous. Fantastic. Thank you! Nov 28, 2013 at 19:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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