Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting SpatVector to sf or sp

Tags:

r

r-raster

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

like image 369
Andrew Plowright Avatar asked Sep 13 '25 07:09

Andrew Plowright


1 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 

You can create an sf object from a SpatVector like this:

s <- sf::st_as_sf(v)

To go in the other direction to create SpatVector from an sf:

vv <- vect(s)

To create an 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 

And you can create a SpatVector from a Spatial* vector type object with

vs <- vect(x)
like image 64
Robert Hijmans Avatar answered Sep 14 '25 20:09

Robert Hijmans