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 ---#
<- as(wells_sf, "Spatial")
wells_sp
#--- 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 ---#
<- st_as_sf(wells_sp)
wells_sf
#--- 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 usingsp
objects than usingsf
objects.↩︎The function does not work for an
sf
object that consists of different geometry types (e.g., POINT and POLYGON). This is becausesp
objects do not allow different types of geometries in the singlesp
object. For example,SpatialPointsDataFrame
consists only of points data.↩︎For those interested in learning the
sp
package, this website is a good resource.↩︎