I have a map (raster) of surface water from Europe. If no water occurs, the cell has a value of 0, when water is present, the cell eqauls 1. The ocean around the continent has "NA" as a value.
There is a layer of cells with value 1 around the continent (the coast). I want to set these to zero as well, since I only want fresh water in my map, not salt water. Basically, I want all cells that are next to the ocean (ocean cells are NA) to become 0.
How can I do this best?
Well, if your raster is a matrix called mat
and is full of integers and NA's I will give you something that might work, make sure you back up your image in another object before you run this, as this is untested code.
iSpinVector = Re(1i**(-1L:2L))
jSpinVector = Re(1i**(0L:3L))
for (i in 2:(nrow(mat)-1)){
for( j in 2:(ncol(mat)-1)){
if(is.na(mat[i,j])){
Neighborhood = cbind(i + iSpinVector,
j + jSpinVector)
mat[Neighborhood] = 0
}
}
}