I have KML file from downloaded https://data.gov.sg/dataset/electoral-boundary_2020. As you can see on the website, there are 31 sub-polygons and each of them has a label. I have loaded the KML on R.
I have a separate .csv data file with postal codes, latitude and longitude. I would like to extract the name of the polygons from the KML file to map to the .csv to give 4 columns:
postal_code latitude longitude Name
Where Name is the name the polygon if the postal_code fall within the polygon. How do I do this using R?
Here is a sample data
library(rgdal)
library(spatialEco)
library(dplyr)
postal_code=c(117606, 640215, 600220, 628389, 118560, 267314, 129580, 268458)
latitude=c(1.283146, 1.348578, 1.340993, 1.303928, 1.277510, 1.321747, 1.315483, 1.322019)
longitude=c(103.7739, 103.7121, 103.7374, 103.6586, 103.7893, 103.7999, 103.7650, 103.7910)
df=cbind.data.frame(postal_code, latitude, longitude)
coordinates(df)<-~longitude+latitude
poly.sg=readOGR('Downloads/doc.kml', "ELD2020")
proj4string(poly.sg)
poly.sg=spTransform(poly.sg, CRS('+init=epsg:4326'))
I have tried to follow the steps in Join spatial point data to polygons in R
poly.sg2<-as(poly.sg, "SpatialPolygonsDataFrame")
pts.poly<-point.in.poly(df, poly.sg2)
I received this error:
Error in st_geos_binop("intersects", x, y, sparse = sparse, prepared = prepared, : st_crs(x) == st_crs(y) is not TRUE
readOGRI can only speculate but, you do not need to coerce to an sp class as, it is already there. Meaning, the polg.sg2 object is not necessary. Besides, thepoint.in.polyfunction handles both sp and sf objects. – Jeffrey Evans Dec 25 '21 at 19:28