I am trying to intersect two spatial objects in R (point and polygon) while preserving the contained information in the dataframes of both.
However, the intersection produces an empty polygon, while both objects do perfectly overlay in QGIS 2.16.2.
After I checked the coordinates of the spatial polygons (test_polys
), I find them strangely altered, such as coordinates like -44524.15 , 167543.0
.
My efforts to change the coordinate system (Step 3) did not succeed. Some ideas how to fix it and explanations, where the coordinate modifications could originate from?
I use R.Studio Version 1.0.143 and rgdal 1.2-8 as well as raster 2.5-8.
Please find the input files in this dropbox folder
And the code I use:
# 1) Initialization -----------------------------------------------------
library(rgdal)
library(sp)
library(raster)
setwd("SET YOUR DIRECTORY")
list.files()
# 2) Read data ----------------------------------------------------------
test_polys <- readOGR(dsn = "C:/YOUR PATH/Desktop/Stackexchange", layer = "Tests_10subsections")
test_points <- readOGR(dsn = "C:/YOUR PATH/Desktop/Stackexchange", layer = "calc_centroids")
test_polys@polygons # Strange coordinates already at this step, such as "-44524.15 167543.0"
# 3) CRS Homogenization -------------------------------------------------
proj4string(test_polys) <- CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
# ERROR "Error in `proj4string<-`(`*tmp*`, value = <S4 object of class "CRS">) : Geographical CRS given to non-conformant data: -45033.0103 167554.5511"
test_polys@proj4string <- CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
test_points@proj4string <- CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
test_points <- spTransform(test_points, CRS(test_polys))
# Error in CRS(test_polys) :
# no method for coercing this S4 class to a vector
# In addition: Warning message:
# In is.na(projargs) : is.na() applied to non-(list or vector) of type #'S4'
# 4) Intersection while preserving point data adding polygon data -------
intersected <- raster::intersect(test_points, test_polys)
# EMPTY "data" with: [1] id Roof_area DTMN11 FR11 SEC11 SS11 BGRI11 LUG11 LUG11DESIG
#<0 rows> (or 0-length row.names)