How can a true intersection/clipping of polygons be done in R?

Problem description: Shapefile1 contains only one feautre without attributes (or - at least - attibutes don't matter). Shapefile2 contains several features, some of them fall entirely, some of the partly in the feature contained in Shapefile1. Other features fall totally outside.

I need to perform a true clip or intersection (just like in QGIS Vector > Geoprocessing Tools > Intersect). So far, the solution is described here. However, in addition to the cited I also DO need the clip to inherit attributes of Shapefile2.

At the end, the result needs to be exported to an ESRI Shapefile.

Any answer, suggestion is welcome!

  • 1
    why not simply use QGis? – Ian Turton Dec 4 '17 at 17:00
  • It would be easier, but I need the process to automated... – Contemplavit Dec 4 '17 at 17:08
  • You should supply sample data, and draw a diagram to explain your process better. – Spacedman Dec 5 '17 at 8:39

Solved with help of this thread.

clipped_geom <- gIntersection(shp1, shp2, byid = TRUE, drop_lower_td = T) #clip polygon2 with polygon1
id_list <- sapply(clipped_geom@polygons, function(x) x@ID)
intersect_list <- gIntersects(shp1, shp2, byid = TRUE)
clipped_data <-  at@data[intersect_list,]
row.names(clipped_data ) <- id_list
clipped <- SpatialPolygonsDataFrame(clipped_geom,clipped_data )

writeOGR(clipped,mypath,"myfile","ESRI Shapefile")

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.