Search code examples
rdistanceraster

Distance raster subset


I calculate a distance raster to compute the distance from the cells of a raster to the red border. The result it is displayed on the following image: Maps discontinuity

Nonetheless, I now want to calculate the distance from all the cells to the inside part of the border (the rightest part of the border). I tried to ´rasterize´ the border, but it is difficult to only select the right part of the border.

Any ideas?

Thanks in advance,

For reproducibility (with available data for all):

library(maptools) #To get the polygon data 
data(wrld_simpl)
colven <- c("Colombia", "Venezuela")
colven_map <- wrld_simpl[wrld_simpl$NAME %in% colven, ]

#Create a raster object
library(raster)
raster <- raster(colven_map, nrow=100, ncol=100)
raster[] <- 1:length(raster)
raster_colven <- mask(raster, colven_map)

#Calculate distance raster
col <- wrld_simpl[wrld_simpl$NAME == "Colombia", ]
ven <- wrld_simpl[wrld_simpl$ NAME == "Venezuela", ]
ven_l <- as(ven, "SpatialLines")
ven_p <- as(ven_l, "SpatialPoints")
distance_raster_colven <- distanceFromPoints(raster, ven_p)
distance_raster_colven <- mask(distance_raster_colven, colven_map)

Solution

  • You can manually select the piece you want:

    plot(ven_l)
    x <- crop(ven_l, drawPoly())
    # draw a polygon on the map
    

    Now

    y <- rasterize(x, raster)
    d <- distance(y)