Search code examples
rggplot2spatialr-sf

How to extract a part of an sf shape in R?


Say that I have the sf type shape data of the US.

usa <- giscoR::gisco_get_countries(country="USA")
# nrow(usa) is 1

Now the usa data provided by the package giscoR includes Alaska and some Pacific islands. Is there any way to extract the contiguous USA as a smaller sf data from the whole shape? Or can I just plot the contiguous USA within the ggplot + geom_sf framework?


Solution

  • You can use sf::st_crop to trim the co-ordinates to whichever you choose, then plot however you like. Here's a full reprex using ggplot:

    giscoR::gisco_get_countries(country = "USA") |>
      sf::st_crop(c(xmin = -125, xmax = -60, ymin = 20, ymax = 60)) |>
      ggplot2::ggplot() + 
      ggplot2::geom_sf()
    #> Warning: attribute variables are assumed to be spatially constant throughout all
    #> geometries
    

    Created on 2023-05-18 with reprex v2.0.2