• API
• FAQ
• Tools
• Archive
SHARE
TWEET # Untitled a guest Jun 25th, 2019 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. library(raster)
2. library(sp)
3.
4. # create rasters and store them in a list
5. r1 <- raster(xmn=1, xmx=5, ymn=1, ymx=5, nrows=4, ncols=4)
6. r1[] <- 1:length(r1)
7.
8. # create SpatialPolygonsDataFrame
9. Sr1 = Polygon(cbind(c(1,5,4,1,1),c(1,2,5,4,1)))
10. Sr2 = Polygon(cbind(c(2,4,3,2),c(3,2,4,3)))
11. SpP = SpatialPolygons(list(Polygons(list(Sr1), "s1"), Polygons(list(Sr2), "s2")),
12.                       1:2)
13. dat = data.frame(ID = c("s1", "s2"), value = c("a", "b"))
14. row.names(dat) <- c("s1", "s2")
15. p <- SpatialPolygonsDataFrame(SpP, data = dat,
16.                               match.ID = TRUE)
17.
19.   # invert the coordinates for Polygons to flag it as a hole
20.   coordsHole <-  hole@polygons[]@Polygons[]@coords
21.   newHole <- Polygon(coordsHole,hole=TRUE)
22.
23.   # punch the hole in the main poly
24.   listPol <- poly@polygons[]@Polygons
25.   listPol[[length(listPol)+1]] <- newHole
26.   punch <- Polygons(listPol,poly@polygons[]@ID)
27.
28.   # make the polygon a SpatialPolygonsDataFrame as the entry
29.   new <- SpatialPolygons(list(punch),proj4string=poly@proj4string)
30.   new <- SpatialPolygonsDataFrame(new,data=as(poly,"data.frame"))
31.
32.   return(new)
33. }
34.
36.
37. p1 <- rbind(p, punchedPoly, makeUniqueIDs = TRUE)
38. p1 <- p1[2:3,]
39.
42.