R sf – Make MULTIPOLYGON Valid When Edges Are Crossing Using S2 Geometry

multi-polygonrsfshapefile

Goal: I would like to know the NUTS region (2016 version) of points in Europe.

Method: (1) Download the official geodata from Eurostat, (2) Use st_join from sf with R.

Problem: I've updated sf, now using v1.0. Now that it uses S2 geometry, I have an error message:

Error in s2_geography_from_wkb(x, oriented = oriented, check = check) : 
  Evaluation error: Found 2 features with invalid spherical geometry.
[821] Loop 0 is not valid: Edge 299 crosses edge 301
[1102] Loop 0 is not valid: Edge 575 has duplicate vertex with edge 579.

Note that it was not generating an error before the update of sf.

Part of a solution: I've used st_make_valid. Now I have a shorter error message:

Error in s2_geography_from_wkb(x, oriented = oriented, check = check) : 
  Evaluation error: Found 1 feature with invalid spherical geometry.
[821] Loop 0 is not valid: Edge 299 crosses edge 301.

Minimal example:

library(sf)
path_to_shape_file_NUTS = "NUTS_RG_01M_2016_4326_LEVL_3.shp"
shape_file_NUTS_WGS84 = st_make_valid(st_read(path_to_shape_file_NUTS, quiet=TRUE))
y_coord <- c(46.976, 46.948)
x_coord <- c(7.483, 7.45)
coordinates_as_df <- data.frame(x_coord, y_coord)
coordinates_WGS84 <- st_as_sf(x = coordinates_as_df, 
                                  coords = c("x_coord", "y_coord"), 
                                  crs = 4326)
overlay <- st_join(coordinates_WGS84, shape_file_NUTS_WGS84, join=st_intersects)
print(overlay)

You should be able to get the shapefile using this link, then opening the zip file "NUTS_RG_01M_2016_4326_LEVL_3.shp.zip" in the zip file.

My question: How to get rid of the error message and get the NUTS region?

Best Answer

The answer by Jindra Lacko is specific to NUTS regions. Just a quick fix if you have an invalid geometry after updating sf to v1.0:

sf_use_s2(FALSE)

It does not solve the problem, but it brings back the old way of working. I still don't have a general solution to make a geometry valid when using S2, but just if it could help someone...