I am trying to iterate over the rows of a spatial polygon data frame in R, but cannot figure out the right indexing. I don't want to select by attributes, but rather just iterate over the spatial polygon data frame.

  • Could you give some sample code, indicate what you've tried? – Simbamangu Jul 16 '15 at 17:35

If you do not need to apply a conditional subset, you can just use a bracket index on rows, without referencing the @data slot.

coordinates(meuse) <- ~x+y

# Subset first observation and plot
p <- meuse[1,]
  plot(meuse, pch=20)
  plot(p, pch=20, cex=1.5, col="red", add=TRUE) 

# display elev value for each observation
for(i in 1:nrow(meuse)) {
  p <- meuse[i,]
  cat("elev", i, p@data$elev, "\n")
  • That is it. I was missing the comma in p <-meuse[1,] – user44796 Jul 16 '15 at 18:39

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.