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.  
  18. AddHoleToPolygon <-function(poly,hole){
  19.   # invert the coordinates for Polygons to flag it as a hole
  20.   coordsHole <-  hole@polygons[[1]]@Polygons[[1]]@coords
  21.   newHole <- Polygon(coordsHole,hole=TRUE)
  22.  
  23.   # punch the hole in the main poly
  24.   listPol <- poly@polygons[[1]]@Polygons
  25.   listPol[[length(listPol)+1]] <- newHole
  26.   punch <- Polygons(listPol,poly@polygons[[1]]@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.  
  35. punchedPoly <-AddHoleToPolygon(p[1,],p[2,])
  36.  
  37. p1 <- rbind(p, punchedPoly, makeUniqueIDs = TRUE)
  38. p1 <- p1[2:3,]
  39.      
  40. masked_hole <- mask(r1, p1)
  41. plot(masked_hole)
  42.      
  43. m3 <- mask(r1, p1[c(2,1),])
  44. plot(m3)
  45.      
  46. r2 <- rasterize(p1, r1, field = "value")
  47. plot(r2)
  48. r3 <- rasterize(p1[c(2,1),], r1, field = "value")
  49. plot(r3)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top