1

I want to extract data of a SpatialPolygonsDataFrame li which intersect with the SpatialPointsDataFrame p R and then create a data frame with the coordinates and values of both objects. I tried

library(sf)

out <- st_intersection(p, li)

I get the error Error in UseMethod("st_intersection") : no applicable method for 'st_intersection' applied to an object of class "c('SpatialPointsDataFrame', 'SpatialPoints', 'Spatial', 'SpatialVector')"

Not all points intersect with the polygon shape.

How could I extract the data of a polygon shape based on a point shape and then create a data frame of the result?

  • You are trying to use a function intended for an "sf" class object, not "sp". There are many posts addressing this exact issue, please search the site! – Jeffrey Evans Jun 28 '18 at 15:36
  • 2
    Possible duplicate of Join spatial point data to polygons in R – Jeffrey Evans Jun 28 '18 at 15:39
  • IMHO not a duplicate, as over doesn't seem to work with sf objects. – Simbamangu Jun 28 '18 at 18:09
1

Be aware that in point.in.poly(), sf is running under the hood. In order to avoid being required to (install and) load yet another package, you might as well take the direct approach (mapview is only needed for the example data here):

library(sf)
library(mapview)

## for the sake of reproducibility, create 'Spatial' example data 
p = as(breweries, "Spatial")
li = as(franconia, "Spatial")

## convert it to 'sf'
p = st_as_sf(p)
li = st_as_sf(li)

## intersect polygons with points, keeping the information from both
pli = st_intersection(li, p)

## transform into a 'data.frame' by removing the geometry
st_geometry(pli) = NULL
head(pli)
0

The answer can indeed partly be found in the linked post Join spatial point data to polygons in R.

I used the packages spatialEco and sp to "merge" the points with the polygons.

library(spatialEco)
library(sp)

pts.poly <- point.in.poly(p, li)
head(pts.poly@data)

Then I transformed the SpatialPointsDataFrame into a data frame by simply using

dat <- as.data.frame(pts.poly)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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