I’ve been encountering an issue while working with spatial data in R. Specifically, I’m getting an error when trying to calculate centroids for my geometries using the st_centroid function from the sf package. The error message is as follows:
Error in st_centroid.sfc(st_geometry(x)) :
not implemented for objects of class sfc_GEOMETRY
Caused by error in wk_handle.wk_wkb()
:
! Loop 7 is not valid: Edge 185 crosses edge 187
Backtrace:
- shapefile_data %>% …
- sf:::st_centroid.sfc(geometry)
- s2::s2_centroid(x)
- sf:::as_s2_geography.sfc(x)
- sf:::st_as_s2.sfc(x, …, oriented = oriented)
- s2:::as_s2_geography.WKB(st_as_binary(x), …, oriented = oriented)
- s2::s2_geog_from_wkb(x, oriented = oriented, check = check)
- wk:::wk_handle.wk_wkb(…)
I’ve tried using st_make_valid
to ensure all geometries are valid, but it hasn’t resolved the issue. Here’s a simplified version of my code:
library(sf)
library(dplyr)
# Load shapefile data
shapefile_path <- "/path/to/shapefile.shp"
shapefile_data <- st_read(shapefile_path)
shapefile_data <- st_make_valid(shapefile_data)
invalid_geometries <- which(!st_is_valid(shapefile_data))
if (length(invalid_geometries) > 0) {
shapefile_data <- st_make_valid(shapefile_data)
}
shapefile_data <- st_transform(shapefile_data, crs = "+proj=longlat +ellps=WGS84 +datum=WGS84")
shapefile_data <- shapefile_data %>%
mutate(centroid = st_centroid(geometry),
lon = st_coordinates(centroid)[, 1],
lat = st_coordinates(centroid)[, 2])
And the map is look wired too:
Despite these steps, the error still persists. I’m not sure how to proceed to make sure each of polygon is close. I would greatly appreciate any suggestions or solutions to handle this issue.
Amy Xiejing is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.