Wednesday, 11 February 2015

r - Clip polygon and retain data?


I have these two polygons:


library(sp); library(rgeos); library(maptools)

coords1 <- matrix(c(-1.841960, -1.823464, -1.838623, -1.841960, 55.663696,
55.659178, 55.650841, 55.663696), ncol=2)
coords2 <- matrix(c(-1.822606, -1.816790, -1.832712, -1.822606, 55.657887,
55.646806, 55.650679, 55.657887), ncol=2)

p1 <- Polygon(coords1)
p2 <- Polygon(coords2)
p1 <- Polygons(list(p1), ID = "p1")
p2 <- Polygons(list(p2), ID = "p2")
myPolys <- SpatialPolygons(list(p1, p2))
spdf1 = SpatialPolygonsDataFrame(myPolys, data.frame(variable1 = c(232,
242), variable2 = c(235, 464), row.names = c("p1", "p2")))
proj4string(spdf1) <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84
+towgs84=0,0,0")
plot(spdf1, col="red")


coords1a <- matrix(c(-1.830219, -1.833753, -1.821154, -1.830219, 55.647353,
55.656629, 55.652122, 55.647353), ncol=2)
p1a <- Polygon(coords1a)
p1a <- Polygons(list(p1a), ID = "p1a")
myPolys1 <- SpatialPolygons(list(p1a))
spdf2 = SpatialPolygonsDataFrame(myPolys1, data.frame(variable1 = c(2),
variable2 = c(3), row.names = c("p1a")))
proj4string(spdf2) <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84
+towgs84=0,0,0")

plot(spdf2, col="yellow", add=T)

enter image description here


I want to cut out parts of spdf1 that are intersected by spdf2. However, I want spdf1 to remain as a SpatialPolygonsDataFrame and to retain any information contained within spdf1@data.


I¹ve tried gDifference as follows, which cuts out parts of spdf1 that are intersected by spdf2, but then converts spdf1 to SpatialPolygons (i.e. discarding information contained in spdf1@data).


gDifference(spdf1, spdf2, byid=T)

How can I cut into spdf1 with spdf2 but retain data contained in spdf1@data? I have checked and tried this similar question without how to overlay a polygon over SpatialPointsDataFrame and preserving the SPDF data?




No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...