'Polygon error when doing a join with INE data in R
I am new to programming in R and I have been asked to update the "Municipality Code" field of our datasets that contain Longitude and Latitude fields. I have to update them with the data from the INE (https://www.ine.es/ss/Satellite?L=es_ES&c=Page&cid=1259952026632&p=1259952026632&pagename=ProductosYServicios%2FPYSLayout) selecting the year 2022, I have to get out of that .shp the "CUMUN" field.
To do this, I loaded the data sets, I gave them the crs 4326 and from my dataset I kept the columns that I wanted. The problem is that when doing a join to keep "CUMUN" and my data is updated, I get this error:
Error in s2_geography_from_wkb(x, oriented = oriented, check = check) :
Evaluation error: Found 14 features with invalid spherical geometry.
[1002] Loop 1 is not valid: Edge 6 has duplicate vertex with edge 64
[3644] Loop 0 is not valid: Edge 4 has duplicate vertex with edge 2290
[6767] Loop 0 is not valid: Edge 136 has duplicate vertex with edge 176
[8002] Loop 0 is not valid: Edge 16 has duplicate vertex with edge 429
[11673] Loop 0 is not valid: Edge 1 has duplicate vertex with edge 407
[12324] Loop 0 is not valid: Edge 0 has duplicate vertex with edge 1331
[13608] Loop 1 is not valid: Edge 486 has duplicate vertex with edge 554
[15429] Loop 0 is not valid: Edge 69 has duplicate vertex with edge 209
[15465] Loop 0 is not valid: Edge 0 has duplicate vertex with edge 300
[15816] Loop 0 is not valid: Edge 58 has duplicate vertex with edge 251
...and 4 more.
I leave you here the code that I have used, later look for which polygons of the .shp file of the INE were not valid with the "st_is_valid" function and those shown in the image appear as invalid.
## Actualizacion de codigos municipio 20220331
# Aqui irian las librerias
library(pacman)
pacman::p_load(leaflet, leaflet.extras, gapminder,mapview,tmap,dplyr,openxlsx, rworldxtra, rgdal,raster, sf, tidyverse,DT, readr, ggthemes)
# Cargamos los datasets.
# INE
spain_seccionado22 <- sf::st_read("SECC_CE_20220101.shp")
spain_4326 <- sf::st_transform(spain_seccionado22, 4326)
# Cargamos nuestros datos
file.choose()
datos.pos =read.xlsx("C:\\xx\\xx\\xx\\xx\\xxx.xlsx")
names(datos.pos)
#Me quiero quedar con el 3 (x), 7 (x), 9 (x), 77 (latitud), 78 (longitud)
datos.pos.mod = cbind(datos.pos[3], datos.pos[7],datos.pos[9],datos.pos[77], datos.pos[78])
datos.posmod_sf = sf::st_as_sf(datos.pos.mod, coords = c("LONGITUD_X", "LATITUD_Y"))
datos.posmod_sf <- sf::st_set_crs(datos.posmod_sf, 4326)
result <- sf::st_join(datos.posmod_sf, spain_4326)
result.df = as.data.frame(result)
test = as.data.frame(st_is_valid(spain_4326))
Here I leave you the image of the polygons of the INE that are supposedly not valid: https://ibb.co/WKkmSPM
Could someone give me a hand? how could i correct this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|