Advertisement
nunosa

Clipping rasters in R

Nov 17th, 2018
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 2.01 KB | None | 0 0
  1. #required packages
  2. library(sp) #not necessary for this set of particular operations but required upon loading raster package
  3. library(raster)
  4.  
  5. #R uses GDAL for these operations on the rasters. It is an equivalent approach.
  6. #more on this: https://geoscripting-wur.github.io/IntroToRaster/
  7.  
  8.  
  9. #downloading worldclim data -------------------------
  10. w.stack = getData('worldclim',
  11.                   var='bio',
  12.                   res=10) #Downloading a WCLIM tile set
  13.  
  14. #If data has already been downloaded:
  15. w.stack = stack("path2file/filename.tif")
  16.  
  17. #both methods load all the bands - to make processing faster we select only one
  18. w.raster <- raster(w.stack,layer=1)
  19.  
  20. #Clipping exercise
  21. #Setting the clip extent
  22. e <- extent(-133.2153004 * 1.05, #xmin
  23.             83.10261     * 0.95, #xmax
  24.             46.81686     * 0.95, #ymin
  25.             58.7162728   * 1.05) #ymax
  26.  
  27. #Clipping command and saving to a file
  28. w.raster.crop <- crop(w.raster, #raster variable
  29.                       e,        #extent variable
  30.                       overwrite=TRUE, #forces overwrite on the output files
  31.                       filename="D:/wclim_b01.asc") #saves file to a given path - any common file extensions can be used here. Some other data types allow compression that saves disk space
  32.  
  33. #Clipping all the all the predictors in the original file
  34. w.stack.crop <- crop(w.stack, #raster stack variable
  35.                      e,        #extent variable
  36.                      bylayer=TRUE, #creates one new raster per each layer in the stack
  37.                      suffix="names", #keeps the original name and uses it for the name of each saved file
  38.                      overwrite=TRUE, #forces overwrite on the output files
  39.                      filename="D:/wclim_.asc") #saves file to a given path - any common file extensions can be used here. Some other data types allow compression that saves disk space
  40.  
  41. #optional:
  42. #The names of each raster can be changed using the command names(w.rstack) which will in turn change the output filenames
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement