'clip raster by SpatialPolygonDataFrame

I have a raster, and want to only retain the sea part of the raster, and remove the land part or the raster. If my raster is "ras" and my SpatialpolygonDataFRame is "worldMap", I tried

ras.msk <-  rgeos::gDifference(ras,worldMap)

however, I get the following error which I do not understand, but I gather that the function can only be used with two spdf's, not with a raster?

Error in RGEOSUnaryPredFunc(spgeom, byid, "rgeos_isvalid") : rgeos_convert_R2geos: invalid R class RasterLayer, unable to convert.

if I do

r2 <- crop(ras, worldMap)
r3 <- mask(r2, worldMap)

I get the land-part of the raster. How do I get the opposite so that the remaining raster excludes the overlapping spatialpolygondataframe area?

The end result I need is all raster point values at sea to be 1, and the raster point values on land to be 0.

My current code is as follows:


# Make raster layer of study area
ras = raster(ext=extent(-70, -55, -60, -38), res=c(0.01,0.01)) #lat/long xmin, xmax, ymin, ymax # 

#give all raster points a "1"
ras[] <- 1

#project the raster 
projection(ras) <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0" 

# load land
library(rworldmap)
worldMap <- getMap(resolution = "high")
projection(worldMap) <- CRS(proj4string(ras))

#crop raster by land
ras.msk <-  rgeos::gDifference(ras,worldMap)



Solution 1:[1]

Need to specify "inverse = T" in the mask function

r2 <- crop(ras, worldMap)
r3 <- mask(r2, worldMap, inverse = T)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user303287