I am trying to calculate the distance from several pixels of a raster to a boundary of some polygons in R as it is showed in the image. I have two problems:
How to correctly define a boundary from a
SpatialPolygonobject. I currently have two options, but I can not decide for which is the best one. First, I can coerce the
SpatialLinesobject and then to SpatialPoints. Second, I can
SpatialPolygon. I suppose each option has its pros and cons.
I only want make the distance calculation from one of the sides of the border. In the example, I only want the distance to the border from the pixels inside Colombia to the border between both countries. I tried to "filter" the border using a latitude parameter but the real border is quite irregular, so using a strict cut-off value can lead to error.
The following code can be used to get the a example shapefile:
#Get the world map and select two countries [Colombia and Venezuela] library(maptools) #To get the shp data data(wrld_simpl) colven <- c("Colombia", "Venezuela") colven_map <- wrld_simpl[wrld_simpl@data$NAME %in% colven, ]
Raster data can be created with this code:
raster <- raster(nrow=100, ncol=100, crs=proj4string(wrld_simpl)) raster_extent <- extent(colven_map) raster <- setExtent(raster, raster_extent) raster <- 1:length(raster) raster_colven <- mask(raster, coven) raster_colven <- crop(raster, colven_map) raster_colven <- mask(raster_colven, colven_map)