Reputation: 525
Does anybody know if there is a built-in function in R terra
to generate a SpatVector polygon from an ext
object, please?
library(terra)
# A SpatExtent object
ext1 <- ext(c(-74.5, -72.5, 9.5, 12.0))
How I manually created the coordinates of the polygon vertices
box_coords <- rbind(
c(ext1[1], ext1[3]),
c(ext1[2], ext1[3]),
c(ext1[2], ext1[4]),
c(ext1[1], ext1[4]),
c(ext1[1], ext1[3])
)
box_coords
# [,1] [,2]
#[1,] -74.5 9.5
#[2,] -72.5 9.5
#[3,] -72.5 12.0
#[4,] -74.5 12.0
#[5,] -74.5 9.5
How I convert the coordinate into a SpatVector
box1 <- vect(box_coords, type = "lines")
The way I'd like it to be, but that doesn't work
box1 <- vect(ext1)
Upvotes: 3
Views: 1287
Reputation: 47536
You can use as.polygons
library(terra)
e <- ext(-74.5, -72.5, 9.5, 12.0)
p <- as.polygons(e, crs="")
# or
p <- as.polygons(e, crs="+proj=longlat")
You can also use as.points
and as.lines
To get a polygon for the extent of SpatRaster or SpatVector x
you can do
x <- rast()
p <- as.polygons(x, extent=TRUE)
The latter has the advantage that the coordinate reference system is not lost, or is less convulted than the alternative
p <- as.polygons(ext(x), extent=TRUE, crs=crs(x))
I have now added this path as well (terra 1.7-6) .
ve <- vect(e, crs="+proj=longlat")
And, to get a numeric vector (not a SpatVector) you can do
as.vector(e)
Upvotes: 4