2

I'm trying to iterate in a SpatialPolygonDataFrame that contains 110 features.

I tried to use the following code with no success:

iterate.spdf = function(x){
    for(i in 1:nrow(x)){
        p = x[i,]
    }
    return(p)
}

It returns with a SpatialPolygonDataFrame that contains only one feature. The code seems to overwrite the polygons to end up with only one feature.

Any suggestions?

2

The failure reason of your code is because the return() statement is out of the loop, but if you place into the loop, the result will be the same. You need to create a list to store each polygon iterated:

# reproducible example
library(sp)
data(wrld_simpl, package='maptools')

# what you have
iterate.spdf = function(x){
  for(i in 1:nrow(x)){
    p = x[i,]
  }
  return(p)
}

length(iterate.spdf(wrld_simpl))
## [1] 1

# a possible workaround
iterate.spdf = function(x){
  p = list()
  for(i in 1:nrow(x)){
    p[[i]] = x[i,]
  }
  return(p)
}

length(iterate.spdf(wrld_simpl))
## [1] 246

class(iterate.spdf(wrld_simpl))
## [1] "list"

You can return a SpatialPolygonDataFrame object also:

# if you want to return a spdf object

library(raster)

iterate.spdf = function(x){
  p = list()
  for(i in 1:nrow(x)){
    p[[i]] = x[i,]
  }
  return(do.call(rbind,p))
}

length(iterate.spdf(wrld_simpl))
## [1] 246
class(iterate.spdf(wrld_simpl))
## [1] "SpatialPolygonsDataFrame"
## attr(,"package")
## [1] "sp"

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.