I am trying to calculate the distances using rnaturalearth.

kr =  ne_countries(returnclass="sf")
d = st_distance(kr[128,],kr) 

but the following error appear:

Error in s2_geography_from_wkb(x, oriented = oriented, check = check) :  
 Evaluation error: Found 3 features with invalid spherical geometry.  
 Loop 2 is not valid: Edge 175 crosses edge 178  
 Loop 1 edge 3 crosses loop 2 edge 1  
 Loop 2 edge 0 crosses loop 6 edge 3.
  • 1
    Use the "r" tag if you are looking for help with any R code - I've added it for you now.
    – Spacedman
    Apr 16, 2022 at 17:05

1 Answer 1


The sf package tries to treat lat-long data as if it made up of great-circle segments connecting points, using spherical geometry. Most geo data is constructed treating lat-long data like its a flat geometry. Interpreting lines between points as curves or straight lines in lat-long space leads to errors like this.

You can switch off this spherical geometry handling with:

> sf_use_s2(FALSE)

And then the distance computation works:

> d = st_distance(kr[128,],kr) 
> d[,1:4]
Units: [m]
[1] 3404071.8 5985371.2  725718.3 3724227.7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.