I have a grid of type SpatialPolygonsDataFrame (each cell has a set of data attributes). I want to merge each cell which has a surface < X with one of its neighbours. An example is depicted in the picture.

enter image description here

I loop over all cells and see which one has to be merged, then I get its neighbors with gTouches, but I couldn't get it work with functions like gUnaryUnion and aggregate.

Here is my code:

for(ix in(1:length(mygridshp))){
   if(mygridshp@polygons[[ix]]@area < 20000){
      neighbor_cells <- gTouches(mygridspolygons[ix], my_other_cells, byid=TRUE);
      neighbor_cells_ids <- my_other_cells$unit_id[neighbor_cells == TRUE];
      if(length(neighbor_cells_ids) > 0){
          first_neighbor <- mygridshp[mygridshp@data$unit_id==neighbor_cells_ids[1],];
          new_cell <- aggregate(rbind(first_neighbor, mygridshp[ix,]));
          new_cell <- gUnaryUnion(spgeom=union(first_neighbor,mygridshp[ix,]));

Any better idea how to do this?

Your Answer

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

Browse other questions tagged or ask your own question.