Converting SpatVector to sf or sp

Viewed 3461

Is there a straightforward way to convert polygonal SpatVector class objects (from the terra library) to either simple features or SpatialPolygonsDataFrames?

Thanks

2 Answers

Example data

library(terra)
f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
v
#class       : SpatVector 
#geometry    : polygons 
#elements    : 12
#extent      : 5.74414, 6.528252, 49.44781, 50.18162  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
#names       : ID_1, NAME_1, ID_2, NAME_2, AREA 

With current terra and sf, you can create a sf object from a SpatVector like this:

s <- sf::st_as_sf(v)

And back to SpatVector:

vv <- vect(s)

Create a sp object from a SpatVector

library(raster)
x <- as(v, "Spatial")
x
#class       : SpatialPolygonsDataFrame 
#features    : 12 
#extent      : 5.74414, 6.528252, 49.44781, 50.18162  (xmin, xmax, ymin, ymax)
#crs         : +proj=longlat +datum=WGS84 +no_defs 
#variables   : 5
#names       : ID_1,     NAME_1, ID_2,   NAME_2, AREA 
#min values  :    1,   Diekirch,    1, Capellen,   76 
#max values  :    3, Luxembourg,   12,    Wiltz,  312 
Related