Search code examples
rrnaturalearth

Error - unable to find an inherited method for function ‘crop’ for signature ‘"sf"’


I have a code that used to work perfectly but, after having reinstalled R, it provides an error. What I'm trying to do is the following:

world <- ne_countries(scale = 110)
atl_extent <- extent(-69, 20, -55, 65)
study_area <- crop(world, atl_extent)

Usually, this would crop perfectly by the coordinates I provided, like this plot.

I've tried also st_crop(world, xmin, ymin, xmax, ymax) but it produces the following error:

Error in wk_handle.wk_wkb(wkb, s2_geography_writer(oriented = oriented,  : 
  Loop 0 is not valid: Edge 0 crosses edge 78

Solution

  • In the current version of rnaturalearth, ne_countries() returns an sf object, so raster(?) methods do not really know what to do with it.

    Your 2nd issue is related to less-than-ideal shapes from Natural Earth combined with sf default mode when dealing with geographical coordinates -- s2 (spherical geometries), it happens to be quite picky when it comes to non-valid geometries. A simple workaround is to disable s2 for that operation.

    library(sf)
    #> Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE
    
    world <- rnaturalearth::ne_countries(scale = 110)
    st_is_valid(world, reason = TRUE)[!st_is_valid(world)]
    #> [1] "Edge 0 crosses edge 78"              
    #> [2] "Loop 0 edge 1 crosses loop 12 edge 5"
    
    sf_use_s2(use_s2 = FALSE)
    #> Spherical geometry (s2) switched off
    world_crop <- st_crop(world, xmin=-69, xmax=20, ymin=-55, ymax=65)
    #> although coordinates are longitude/latitude, st_intersection assumes that they
    #> are planar
    #> Warning: attribute variables are assumed to be spatially constant throughout
    #> all geometries
    sf_use_s2(use_s2 = TRUE)
    #> Spherical geometry (s2) switched on
    
    plot(world_crop$geometry)