Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. library(sp)
  2. library(raster)
  3.  
  4. # Create Raster
  5. r <- raster(ncol=40, nrow=20)
  6. r[] <- rnorm(n=ncell(r))
  7.  
  8. # Create Polygon
  9. a <- seq(-150,150,1)
  10. b <- 50*a^2/(150^2)
  11. df <- data.frame(a=a,b=b)
  12. srl <- Polygon(df, hole=as.logical(NA))
  13. Srl <- Polygons(list(srl), 1)
  14. poly <- SpatialPolygons(list(Srl), pO = 1:length(Srl), proj4string=CRS(as.character(NA)))
  15.  
  16. # Plot raster and polygon
  17. plot(r)
  18. plot(poly, add=T)
  19.  
  20. # Mask and plot
  21. rr <- mask(r, poly)
  22. plot(rr)
  23.  
  24. # The previous code snippet must be executed prior to this one
  25. e1 <- c(-180,180,180,-180)
  26. e2 <- c(90,90,-90,-90)
  27. df2 <- data.frame(e1=e1,e2=e2)
  28. srl2 <- Polygon(df2, hole=F)
  29. Srl2 <- Polygons(list(srl2), 2)
  30. poly2 <- SpatialPolygons(list(Srl2))
  31. srl3 <- Polygon(df)
  32. Srl3 <- Polygons(list(srl3), 1)
  33. poly3 <- SpatialPolygons(list(Srl2,Srl3))
  34.  
  35. hole <- poly
  36. polyX <- poly2
  37. coordsHole <- hole@polygons[[1]]@Polygons[[1]]@coords
  38. newHole <- Polygon(coordsHole,hole=TRUE)
  39. listPol <- polyX@polygons[[1]]@Polygons
  40. listPol[[length(listPol)+1]] <- newHole
  41. punch <- Polygons(listPol,polyX@polygons[[1]]@ID)
  42. new <- SpatialPolygons(list(punch),proj4string=poly@proj4string)
  43.  
  44. plot(r)
  45. plot(new, col="white", border="NA", add=T)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement