0

require: raster package

I am having trouble masking values of one raster using values in another. This is similar to this question:

https://stackoverflow.com/questions/51716315/how-to-subset-classify-raster-based-on-another-raster-grid-cells-values

but it doesn't have the moving window (focal function) as a component of the question. I have two rasters with the same dimension, extent, projection.

Raster "MAT2resampled" is a raster with a wide range of temperature indices enter image description here Raster "wintPCP" is a second raster with pixel values of 1, O, and NA enter image description here

The only pixels I want from MAT2resampled are those with the value 1 in wintPCP.

I used this code: PthreshWint2 <- mask(MAT2resampled, wintPCP)

When I plot PthreshWint2, it doesn't appear as though the MAT2resampled raster has been masked at all. I think I'm missing something simple.

enter image description here

I have posted the two rasters here: https://drive.google.com/open?id=118kCu6QpoXSYmA17PpODRhHDJefHPkx1

https://drive.google.com/open?id=1N062TiHTHBqRYrclRW8O87WY-MX8taQg

  • Change the values of 0 in wintPCP to NA first then mask – Stefano Potter Oct 8 at 18:29
  • 1
    Please try and make examples with smaller data sets - these are way too large for many people to bother downloading. If you can create sample data in code then that's even better. – Spacedman Oct 8 at 19:29
1

First change the values of 0 in wintPCP to NA:

wintPCP[wintPCP == 0] <- NA

then mask:

masked_ras <- mask(MAT2resampled, wintPCP)

  • Thanks! That worked. Wasn't obvious that I needed to include that step. – Sean Basquill Oct 9 at 13:02
1

You have a mask with 0, 1, and NA values and you want to keep only the 1s. Hence you need to convert 0 and NA to the same value.

Here's a bit of a trick. Diving m by itself results in NA where m is 0 or NA (since 0/0 returns NaN, which acts like NA in mask) and 1 where its 1:

rmask = mask(r,m/m)

not sure if that's any quicker than the other solutions.

  • Thanks. That's a slick little trick. Appreciate the help – Sean Basquill Oct 9 at 13:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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