PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 28, 2022

[FIXED] how to crop raster based on SpatialPolygons in R

 July 28, 2022     crop, r, r-raster, sp     No comments   

Issue

I would like to crop a raster based on SpatialPolygons object. I know that we can use crop function in raster package,

raster::crop(rasterFile, SpatialPolygonsObject)

but this function is based on the extent of SpatialPolygons object, so the cropped result is rectangle. However, in some case, SpatialPolygons object is not rectangle, how to deal these situations?


Solution

You can use raster::mask. Here's a reproducible example:

library(raster)
r = raster(vals = rnorm(400), nrows=20, ncols=20, ext= extent(c(0, 20, 0, 20)))
p = Polygon(matrix(5, 5, 15, 12, 7, 16, 3, 10), ncol=2, byrow = T))
p = SpatialPolygons(list(Polygons(list(p), "p")))

plot(r)
lines(p)

enter image description here

r2 = mask(r,p)
plot(r2)

enter image description here

If you also need to clip the extent of the raster to remove empty rows and columns around the mask, then you can either use crop before applying mask, or you can use trim(r2, values = NA) afterwards.



Answered By - dww
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing