Recently, I have been working on processing data from multiple sites, which involved calculating the distance to the nearest coastline for the study sites. After exploring various methods in R and ArcGIS to compute the shortest distances, I found that many were complex and tedious. However, by integrating ideas from different sources, I’ve developed a simplest and fastest approach for calculating the shortest distance for each site by using R. This method is capable of processing multiple sites at the same time. I’d happy to share my codes below. Please feel free to let me know if you have any questions 🙂
# Load library
library(ggOceanMaps) # in order to use its function dis2land, the output are in kilometers.
library(rnaturalearth)
library(sf)
# Load coastline data
coast <- ne_coastline(scale=10, returnclass = “sf”)
Your_sites <- read.csv(“Your_sites.csv”)
# For example, I have a csv file called "Global sites", with three columns: sites_codes, Longitude (LON), and latitude (LAT):
# Calculate the shortest distance
ggOceanMaps::dist2land(Your_sites,shapefile =coast)
# The results will look like: ldist is the shortest distance (kilometers).
# Additional explanations:
The usage of ggOceanMaps library: We will use its function called “dis2land” to calculate the shortest distance. The function was originally designed for calculating the distance from a point in the ocean to the land (reference: R/dist2land.R ). But we can replace the shapefile of the ocean by the shapefile of the coastline, so that we can calculate distance to the closest shoreline. The output is “ldist” and it is in kilometers.
The usage of rnaturalearth library: we can get the global coastline shapefile with the available finest resolution (scale =10) directly from this library.
The method presents here is inspired by Mikko’s answer at https://stackoverflow.com/questions/51837454/r-measuring-distance-from-a-coastline.