R Polygon Intersection – Rgeos Drops Associated Values When Intersecting Polygons

intersectionpolygonr

I am trying to intersect two SpatialPolygonsDataFrames and get a SpatialPolygonsDataFrame as the result. Unfortunately, using the gIntersection function from rgeos (which works impressively quickly to intersect the polygons), I cannot seem to retrieve the associated dataframes. Consider the following example:

> fracPoly <- gIntersection( toSingle, fromSingle )
> class(toSingle)
[1] "SpatialPolygonsDataFrame"
> class(fromSingle)
[1] "SpatialPolygonsDataFrame"
> class(fracPoly)
[1] "SpatialPolygons"

I can write a wrapper function which handles the transfer of data.frames, but it will be a minor pain to get all the checking right and before I did I was hoping someone could either confirm that there's no better way or point me towards another function (or option for gIntersection) which would allow me to retain the associated data.frames.

Update

On further reflection, this may may be very deliberate behavior by gIntersection. After all, of the two SPDFs, whose data.frame do you pass along? So I may have to write a wrapper which merges the two.

Best Answer

The behaviour of gIntersection is not to pass any intersected data by design:

Since there are no general matches between intersected spatial objects, any arbitrary operations on attributes require assumptions about unknown user intentions. This is why no data slots should be passed through ...

... The design of gIntesection() is inentional, because only the user can know what to do with attributes of entities that have their geometries changed. Different users may make different assumptions, but there is no general solution beyond passing through the IDs of the intersecting geometries, as is done in the row.names() mechanism.

To my surprise, the raster package has a intersection function, which simply intersects and hands over the data as well.

The raster package has a few functions that extend rgeos by also attempting to handle attribute data as well. In this case, see raster::intersect And the list of functions here: ?"raster-package" (section XIV)

The complete info I got on this: http://r-sig-geo.2731867.n2.nabble.com/Intended-usage-of-gIntersection-td7587120.html