[GIS] Mask raster function in R not working to extract values in one raster based on conditions in another

extract-by-maskrraster

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

Best Answer

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.