I have two raster objects, crop both to the same extent and mask all values within raster 1 that do not lie in the range of the values of raster 2.
suit_hab_45_50_Env <- futureEnv_45_50_cropped<maxValue(currentEnv_summer_masked)
suit_hab_45_50_Env <- suit_hab_45_50_Env*futureEnv_45_50_cropped
suit_hab_45_50_Env <- mask(futureEnv_45_50_cropped, suit_hab_45_50_Env, maskvalue=0)
suit_hab_45_50_Env <- crop(suit_hab_45_50_Env, currentEnv_summer_masked)
suit_hab_45_50_Env <- mask(suit_hab_45_50_Env, currentEnv_summer_masked)
plot(suit_hab_45_50_Env)
writeRaster(suit_hab_45_50_Env, filename = "suit_hab_45_50_Env", format = "GTiff", overwrite = TRUE)
Is there a way that R tells me how much % of the area in raster 1 has been masked?
Or in other words: The grey polygon = 100% and the overlaying raster layer covers x % of the polygon.
As you are working in a geographic coordinate system, and especially as you are working in a high latitude area, you cannot simply compare the number of non-NA pixels, as pixels at higher latitudes are smaller than those at lower latitudes. You must use the latitude to calculate the area of each pixel and then sum these to get the area of each raster. Here is an example using cropped vs masked rasters of Canada and the raster::area
function that takes the latitude of each pixel into account when calculating pixel area:
require(raster)
require(maptools)
##get shapefile of canada
data("wrld_simpl")
can_shp=wrld_simpl[which(wrld_simpl$NAME=="Canada"),]
##create empty raster of the world
rs=raster()
##crop canada
rs_can=crop(rs,can_shp)
##calaculate area of each pixel
crop_area=area(rs_can)
plot(crop_area) ##note cells are smaller at higher latitudes
lines(can_shp)
##calculate crop area
crop_area_total=sum(crop_area[])
##mask canada
mask_area=mask(crop_area,can_shp)
plot(mask_area)
lines(can_shp)
##calculate mask area
mask_area_total=sum(mask_area[],na.rm=T)
mask_area_total
# [1] 9793736
# which is not far from the wikipedia reported 9,984,670 km2
# the under-estimate is due to the coarse resolution of the raster
##calculate percentage
mask_area_total/crop_area_total*100
# [1] 48.67837
N.B. You've mis-labelled lat and long :)