I downloaded a shapefile that has a linestring object that represent the coastline of country (Brazil) and after importing this SHP-file into R i have a geometry vector of 630 rows of the type "linestring z". I am assuming those are the 630 pieces that together make up the coastline. I have the longitudes and latitudes of 5570 places in a second dataframe (called df2) and I want to measure the minimum distance of each of these 5570 points to the coastline object, but somehow the distances do not make sense. Does someone know how to do this? The line string shapefile is from here: https://geodata.lib.berkeley.edu/catalog/sde-columbia-iscgm_brazil_2007_coastl my code is as follows:
lon_lat<-annual_panel%>%ungroup()%>%distinct(lon, lat)
# convert to sf object
lon_lat_sf <- lon_lat %>% st_as_sf(coords = c('lon','lat')) %>%
st_set_crs(4326)
#load coastline data
coastline <- st_read(here("raw","coastline data","columbia_iscgm_brazil_2007_coastl.shp"))
# Measure distances between each municipality and the linestrings
distances <- st_distance(lon_lat_sf, coastline$geometry)
# Find the minimum distance for each municipality
min_distances <- apply(distances, 1, min)
I expected to get the minimum distance of each of the 5570 locations to the coastline but the distances provided by st_distance do not seem to be correct, hence there must be an error from my side somewhere.
If you have multiple shapes for a coastline, you may want to consider picking the longest one (assuming all the rest are for islands) or first creating a union; this way you'll end up with a 5570 x 1 matrix instead of 5570 x 640.
If you are not bound to that specific shapefile,
{giscoR}provides convenient access to coastal linestrings:Created on 2023-08-18 with reprex v2.0.2