How to multiply a raster based on grid cell values

My next question builds on the solution suggested by @jbaums in this post: Global raster geographic path

To reproduce the example, I have a raster dataset of distances to the nearest coastline:

library(rasterVis); library(raster); library(maptools)
data(wrld_simpl)

# Create a raster template for rasterizing the polys. 
r <- raster(xmn=-180, xmx=180, ymn=-90, ymx=90, res=1)
# Rasterize and set land pixels to NA
r2 <- rasterize(wrld_simpl, r, 1)
r3 <- mask(is.na(r2), r2, maskvalue=1, updatevalue=NA) 
# Calculate distance to nearest non-NA pixel
d <- distance(r3) # if claculating distances on land instead of ocean: d <- distance(r3)
# Optionally set non-land pixels to NA (otherwise values are "distance to non-land")
d <- d*r2 
levelplot(d/1000, margin=FALSE, at=seq(0, maxValue(d)/1000, length=100),colorkey=list(height=0.6), main='Distance to coast (km)') 

      

The data looks like this: output plot

From here I need a subset of the raster (d) or create a new raster that contains only cells for which the distance to the coastline is less than 200 km. I have tried using getValues ​​() to identify cells for which the value is <= 200 (as shown below), but so far with no success. Can anyone please help? Am I on the right track?

#vector of desired cell numbers
my.pts <- which(getValues(d) <= 200)
# create raster the same size as d filled with NAs
bar <- raster(ncols=ncol(d), nrows=nrow(d), res=res(d))
bar[] <- NA
# replace the values with those in d
bar[my.pts] <- d[my.pts]

      

+3


source to share


1 answer


I think this is what you are looking for, you can treat a raster like a matrix right after the line d <- d*r2

:

d[d>=200000]<-NA
levelplot(d/1000, margin=FALSE, at=seq(0, maxValue(d)/1000, length=100),colorkey=list(height=0.6), main='Distance to coast (km)') 

      



(in case you forgot: the device is in meters, so the threshold should be 200000, not 200)

+3


source







All Articles