rgis

How can I extract the coordinates from the coastal part of this sf object in R?


Using the rnaturalearth package, I have been able to produce a map of Atlantic like so.

library(rnaturalearth)
library(rnaturalearthdata)

#Load Canada from Natural Earth
canada_dl = ne_countries(scale = 110, country = "Canada")
#Plot Canada, but only the Atlantic Canada bits 
canada_atlantic_only = st_crop(canada_dl, xmin = -70, xmax = -50 , ymin = 41, ymax = 61)

This is what the map itself looks like, and I'm okay with that.

enter image description here

What I would like to do is to start along the coastline of this map, and then extract coordinates along that line. I will be using those coordinates draw other lines to points closer and further offshore, but basically I don't know how to ask R to give me the coordinates of the line which represents the coastline of Atlantic Canada. Is there a way to use rnaturalearth to do that?


Solution

  • I suppose that you are ok with your definition of the Atlantic, but there is a shared border with USA. It's not clear if polylines are wanted, or coordinates of points

    With the package sf, st_boundary() is usefull to transform the polygons to polylines. st_difference allow to remove the border with the USA. The first points of the polylines are printed as coordinates , another good solution has been made by L Tyrone.

    (I removed some warnings )

    library(rnaturalearth)
    library(rnaturalearthdata)
    library(sf)
    
    library(tidyverse)
    
    #Load Canada from Natural Earth
    canada_dl = ne_countries(scale = 110, country = "Canada")
    #Plot Canada, but only the Atlantic Canada bits 
    canada_atlantic_only = st_crop(canada_dl, xmin = -70, xmax = -50 , ymin = 41, ymax = 61)
    
    
    # Get USA boundary
    us_boundary = ne_countries(scale = 110, country = "United States of America") %>%  st_boundary()
    
    can_boundary  <-canada_dl  %>%  st_boundary()
    
    coast_boundary = st_difference(can_boundary,us_boundary ) %>% 
      st_crop(canada_dl, xmin = -70, xmax = -50 , ymin = 41, ymax = 61)
    
    ggplot() + geom_sf(data =  coast_boundary )
    

    
    print(coast_boundary %>% st_coordinates() %>% head() )
    #>              X        Y L1 L2
    #> [1,] -69.59157 61.02989  1  1
    #> [2,] -69.62033 60.22125  1  1
    #> [3,] -69.28790 58.95736  1  1
    #> [4,] -68.37455 58.80106  1  1
    #> [5,] -67.64976 58.21206  1  1
    #> [6,] -66.20178 58.76731  1  1
    

    Created on 2024-11-01 with reprex v2.1.0