I am using the randomPoints function in the dismo package in R to generate random points from a raster stack. The documentation for the randomPoints function says:
"The points are sampled (without replacement) from the cells that are not 'NA' in raster 'mask'."
I successfully sample random points from my raster stack
rs, which consists of 9 raster layers, and put the points into a data frame for easier handling.
bg <- as.data.frame(randomPoints(mask = rs, n = 5000)) length(bg[,1])  5000
All of the points generated are valid points:
sum(is.na(bg))  0
To check whether any of these points are NA in the mask raster stack, I extract the raster stack over the points:
ext <- extract(rs, bg) dim(ext)  5000 9
Now I check whether there are any NA's. There shouldn't be, because the randomPoints function should exclude cells of the mask raster that are NA. But still:
sum(is.na(ext))  2303
When I look through the
ext data frame, I see that the NA's seem to be pretty randomly scattered through the raster stack. It's not one raster layer in particular that has all the NA's, and points that are NA in one layer aren't necessarily NA in the others. I understand that perhaps the non-NA values in my raster layers don't perfectly match up, but regardless, these should have been excluded by the randomPoints function, no?
Just to make sure, I tried this again, but this time I selected the background points using only one layer of the raster stack as the mask.
bg1 <- as.data.frame(randomPoints(mask = rs[], n = 5000))
Now, when I check for NA values in the extractions, there are indeed no NA values for the raster that was used as the mask, but there are still NA values in some of the other rasters for some of the points.
It seems that passing a raster stack to the randomPoints function, instead of a single raster layer, does not result in the function excluding cells that are NA in any of the layers in the stack.
Does anyone know the best way to deal with this, if I need to have background points that are not NA in any of the raster layers in the stack? It's easily possible that there is slight misalignment in my raster layers (perhaps at land-water boundaries), but they all cover the same area and are, for the most part, well-aligned. All I can think of is to select background points, extract them over the rasters, and then exclude those that have at least one NA value, but a.) this is tedious and b.) I need to ensure that I end up with a given number of random points; since the number of NA's resulting is unpredictable, I'm not sure how to make this work.