point.in.poly function does not work because it is deprecated?

120 Views Asked by At

I've extracted coordinates for some address using Open Street Map in R and to ensure geocoding is correct, I want to check if the coordinates I found fall within the citys' boundaries.

cities <- readOGR("cities")
crs_project<-("+proj=longlat +datum=WGS84 +no_defs")

coordinates(extracted_gps)<-~lon+lat
proj4string(extracted_gps)<-CRS("+proj=longlat +datum=WGS84 +no_defs")
extracted_gps<-spTransform(extracted_gps, CRS(crs_project))

extracted_gps <- spatialEco::point.in.poly(extracted_gps, cities)

When I try to do this, I receive the following error:

Warning message:
Function is deprecated because sf::st_intersection
    intersections points an polygons and returns associated
         attributes

Trying to run sf::st_intersection, I get this:

extracted_gps <- sf::st_intersection(extracted_gps, cities)

Error in UseMethod("st_intersection") : 
  no applicable method for 'st_intersection' applied to an object of class "character"

The cities is a SpatialPolygonsDataFrame and extracted_gps is a Formal class SpatialPointsDataFrame.

1

There are 1 best solutions below

0
Akhilesh Pandey On

You need to convert your sp objects to sf objects. You can do this using the st_as_sf() function from the sf package.

Here you can do this,

# Convert sp objects to sf
cities_sf <- sf::st_as_sf(cities)
extracted_gps_sf <- sf::st_as_sf(extracted_gps)

# use sf functions
extracted_gps_sf <- sf::st_intersection(extracted_gps_sf, cities_sf)

The st_as_sf() function converts sp objects to sf objects, allowing you to use the newer sf functions on them. The st_intersection() function can then be used on these sf objects without issue.