Global Raster of geographic distances

删除回忆录丶 提交于 2019-12-04 16:31:54

You can do this with raster::distance, which calculates the distance from each NA cell to the closest non-NA cell. You just need to create a raster that has NA for land pixels, and some other value for non-land pixels.

Here's how:

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

To create the plot above (I like rasterVis for plotting, but you could use 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')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!