1

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.

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

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

library(sp)
data(meuse)
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")
}
1
  • That is it. I was missing the comma in p <-meuse[1,] – user44796 Jul 16 '15 at 18:39
0

Using the "split" function of the base library allows to use apply -style iterators (faster than "for" loops and much more memory-efficient for big datasets)

e.g :

library("rgdal")

shp<-"MY_SHP_PATH"
my_layer <- readOGR(shp , GDAL1_integer64_policy = TRUE)
split_layer=split(my_layer , my_layer$KEY_FIELD)
sapply(split_layer, function(my_geom)
{
   #GET ID
   id<-my_geom$ID_FIELD
   #GET NAME
   name<-my_geom$NAME_FIELD
   #GET elevation
   elevation<-my_geom$ELEVATION_FIELD

   # + to get the geometry (if there is only one polygon shape in the item)
   #...otherwise iterate on "polygons"...
   coords_poly<-my_geom@polygons[[1]]@Polygons[[1]]@coords

   #etc... 
 })

`

This should also work for points ("SpatialPointsDataFrame") and related types...

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.