问题
I apologise in advance for the very basic nature of this question, but I'm confused about how the mask() function works in the raster package in R.
Reading the documentation for the function it sounds like cells in raster x are set to NA (the default) if these cells match a maskvalue in a mask object (the default maskvalue being NA). However, the description of the mask() function in the book Geocomputation with R by Lovelace et al. (https://geocompr.robinlovelace.net/spatial-operations.html#spatial-ras) (section 4.3.1) makes it sound as if cells in raster x are KEPT if they match a maskvalue in a mask object, and set to NA if they don't. They give this example:
mask(elev, rmask, maskvalue = TRUE)
"we only want to keep those values of elev which are TRUE in rmask"
Hence my confusion. I would be grateful if someone could clarify which interpretation is correct.
The reason I'd like to know is that I'd like to mask a raster containing MODIS data on percentage tree cover with a raster from the same MODIS product that contains data quality codes. I'd like to retain only those values in the "tree cover" raster that have "good quality" quality codes in the "quality" raster. Clarifying how the mask() function works will help me to determine whether I need to use code [1] or code [2] to achieve what I want:
[1]
good <- c(0,1,2,3,4,5...etc.) # The codes in the quality raster that represent good quality data
tree_cover_masked <- mask(tree_cover, quality, maskvalue = good, inverse = TRUE)
# i.e. set cells in tree_cover to NA if they match any value OTHER THAN the "good" values in the quality raster.
# This is the code I would use based on my interpretation of the function documentation.
[2]
tree_cover_masked <- mask(tree_cover, quality, maskvalue = good)
# i.e. keep values in tree_cover that match "good" values in the quality raster, and set all others to NA
# This is the code I would use based on my interpretation of Lovelace et al.
Apologies again if this question is very simplistic, but I'd be grateful for your help!
回答1:
What stops you from making a small example and test which approach works? In your case, neither [1] nor [2] will work, as maskvalue is a single value (the first value if you provide a longer vector). You probably want to use reclassify first
Example data
library(raster)
qual <- trees <- raster(nrow=4, ncol=4, xmn=0, xmx=1, ymn=0, ymx=1, crs='+proj=utm +zone=1')
values(trees) <- rep(1:4, 4)
values(qual) <- rep(1:8, 2)
Create a RasterLayer with good (4 - 8) and bad (1 - 8) values and then use mask
good <- reclassify(qual, rbind(c(0, 4, NA), c(4, 9, 1)))
# this would also work
# good <- reclassify(qual, cbind(0, 4, NA))
x <- mask(trees, good)
Or:
good <- subs(qual, data.frame(from=c(5,6,7,8,9), 1))
x <- mask(trees, good)
来源:https://stackoverflow.com/questions/50822233/confusion-about-the-mask-function-in-the-raster-package