2.7 Conversion to and from sp objects
You may find instances where sp objects are necessary or desirable.49 In that case, it is good to know how to convert an sf object to an sp object, vice versa. You can convert an sf object to its sp counterpart using as(sf_object, "Spatial"):
#--- conversion ---#
wells_sp <- as(wells_sf, "Spatial")
#--- check the class ---#
class(wells_sp)[1] "SpatialPointsDataFrame"
attr(,"package")
[1] "sp"
As you can see wells_sp is a class of SpatialPointsDataFrame, points with a data.frame supported by the sp package. The above syntax works for converting an sf of polygons into SpatialPolygonsDataFrame as well50.
You can revert wells_sp back to an sf object using the st_as_sf() function, as follows:
#--- revert back to sf ---#
wells_sf <- st_as_sf(wells_sp)
#--- check the class ---#
class(wells_sf)[1] "sf" "data.frame"
We do not cover how to use the sp package as the benefit of learning it has become marginal compared to when sf was just introduced a few years back51.
For example, those who run spatial econometric methods using
spdep, creating neighbors from polygons is a bit faster usingspobjects than usingsfobjects.↩︎The function does not work for an
sfobject that consists of different geometry types (e.g., POINT and POLYGON). This is becausespobjects do not allow different types of geometries in the singlespobject. For example,SpatialPointsDataFrameconsists only of points data.↩︎For those interested in learning the
sppackage, this website is a good resource.↩︎