3

I have daily rainfall values in a NetCDF (.nc) file which is of larger extent covering a catchment area of a river basin. I want to crop it and extract the rainfall values that are within the catchment area. I have a shapefile of the catchment area. I am working in R and did like this:

crop(raster,e,filename="cropped_pr.nc",snap='near') 

raster=source file

e<-extent(reference_raster) #extent of catchment area (rectangular boundary)

It crops the source file in a rectangular shape, as expected in the script, and includes values that are outside the catchment area too. However, the catchment area is not rectangular (polygon).

I want to make the values outside the catchment area as 0. It means I want the values which are within the catchment area only.

0

2 Answers 2

3

You can use your polygon as mask.

# r = your_raster
# p = SpatialPolygons(your_polygon)

r_masked <- raster::mask(r, p)

Outside of your polygon will be filled by NA

Then you will probably want to trim unnecessary margins, while replacing NA by 0.

r_trimmed <- trim(r_masked, values = NA)
r_trimmed[is.na(r_trimmed)] <- 0
2
  • Thank you. I used shapefile and mask function in a cropped file. It worked for me.
    – Santosh
    Commented Oct 28, 2018 at 23:18
  • @Santosh Yes, thanks! As you have already cropped it, that makes perfect sense.
    – Kazuhito
    Commented Oct 30, 2018 at 12:53
0

The crop function subsets to a new rectangular extent and mask turns all values outside the mask area to NA but, does not subset the extent. As such, you want to use the two functions in conjunction eg, mask(extent(x, e), m)

1
  • Thank you. I used shapefile and mask function in a cropped file. It worked for me.
    – Santosh
    Commented Oct 28, 2018 at 23:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.