jba*_*ums 10
您可以使用raster::distance它来计算从每个NA单元格到最近的非NA单元格的距离.您只需创建一个具有NA陆地像素的栅格,以及非陆地像素的其他值.
这是如何做:
library(raster)
library(maptools)
data(wrld_simpl)
# Create a raster template for rasterizing the polys.
# (set the desired grid resolution with res)
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)
# Optionally set non-land pixels to NA (otherwise values are "distance to non-land")
d <- d*r2
Run Code Online (Sandbox Code Playgroud)
要创建上面的图(我喜欢rasterVis绘图,但你可以使用plot(r)):
library(rasterVis)
levelplot(d/1000, margin=FALSE, at=seq(0, maxValue(d)/1000, length=100),
colorkey=list(height=0.6), main='Distance to coast')
Run Code Online (Sandbox Code Playgroud)