Search code examples
rdistancerastershapefilerasterize

Global Raster of geographic distances


Im wondering if someone has built a raster of the continents of the world where each cell equals the distance of that cell cell to the nearest shore. This map would highlight the land areas that are most isolated inland.

I would imagine this would simply rasterize a shapefile of the global boundaries and then calculate the distances.


Solution

  • 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.

    enter image description here

    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')