1
votes

I have a raster to use as a mask (called mask.in) that has 259200 total cells with the following statistics.

summary(mask.in)
         layer
Min.         1
1st Qu.      1
Median       1
3rd Qu.      1
Max.         1
NA's    250864

A brick called tmax has the same xy dimensions and 3,563 layers. The statistics for one of the layers is

summary(tmax[[100]])
          X2051.04.10
Min.       -33.302513
1st Qu.      3.263116
Median      16.360193
3rd Qu.     31.013544
Max.        46.200554
NA's    193403.000000

The NA values are where there is ocean. The numeric values are for land areas. Now I want to mask out areas for a particular part of is brick using this mask. I use this command tmax_cropArea <- mask(tmax, mask.in). My expectation is that the number of NAs in tmax_cropArea should be greater than in tmax (something like 193403 + 250864. But instead all the NAs seem to be converted to zero. How do I get the NA values to stay as NAs. I have tried tmax_cropArea <- mask(tmax, mask.in, maskvalue = NA) but get the same result.

summary(tmax_cropArea[[100]])
        X2051.04.10
Min.      -8.521704
1st Qu.    8.933283
Median    14.269220
3rd Qu.   21.175379
Max.      44.941521
NA's       0.000000
1

1 Answers

1
votes

This works fine in an example with raster 3.1-5

library(raster)
#rasterOptions(todisk=TRUE)
r <- raster(ncol=10, nrow=10)
m <- raster(ncol=10, nrow=10)
set.seed(1)
values(r) <- runif(ncell(r)) * 10
rr <- r * 10
r[1:10] <- NA
s <- stack(r, rr, r+10)
values(m) <- runif(ncell(r))
m[m < 0.5] <- NA
mr <- mask(s, m)

freq(r, value=NA)
#[1] 10
freq(m, value=NA)
#[1] 45
freq(mr, value=NA)
#layer.1 layer.2 layer.3 
#     49      45      49 

summary(mr[[3]])
#         layer.3
#Min.    10.13390
#1st Qu. 13.04938
#Median  14.76351
#3rd Qu. 17.68076
#Max.    19.34705
#NA's    49.00000

You are not showing an actual script, and we do not have your data, making it harder to help. I would first try this on one layer, and visually inspect the result (and inspect some individual cells --- perhaps from coordinates obtained with click()). Are the values indeed zero where they should be NA --- you show that there are no NAs, but not that they are zero.