rspatial / raster

R raster package https://rspatial.github.io/raster/reference/raster-package.html
GNU General Public License v3.0
161 stars 52 forks source link

error in trying to use crop for a bounding box #293

Closed dsteinke2017 closed 2 years ago

dsteinke2017 commented 2 years ago

Hi there, I am getting this error: Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘extent’ for signature ‘"SpatVector"’

I modified some code by Russell J Gray (https://www.rjgrayecology.com/blog/ecoregions-maps-in-r#/) to build a bounding box around one country to later display a map with ecoregions within it. Works fine until I am trying to use crop (leads to error). Here the part of the code:

#get a world object with all countries
library(rnaturalearth)
world <- ne_countries(scale = "medium", returnclass = "sf")
world.MA <- subset(world, subregion=="Central America")
#get central points and coordinates to label the country names
world_points<- st_point_on_surface(world)
world_points <- cbind(world, st_coordinates(st_point_on_surface(world$geometry)))
#located and plot mapping points in subregion/continent
MA <- subset(world_points, subregion == "Central America")
#subset Costa Rica
CR <- subset(MA, iso_a3 == "CRI")

#get shapefile
list.files(pattern=".shp")
eco.regions <- readOGR(getwd(), "tm_ecoregions_2017")
#get ecoregion for 
eco.regions.SA <- subset(eco.regions, REALM=="Neotropic")
eco.df <- fortify(eco.regions.SA, region ="ECO_NAME")
# create a bounding box around Costa Rica
bbSP <- bboxSpatialPolygon(boundingbox = extent(CR))
# fortify the shape file
eco.simp <- crop(eco.regions, extent(bbSP))

Many thanks for any help. Tried this in terra as well, same result.

rhijmans commented 2 years ago

This is not the place for general "how to" questions. I would suggest stackoverflow or gis.stackexchange,com. In either case, please make your script reproducible. For example, you need to include the libraries and (example) data used.

Anyway, what you can do is something along these lines:

library(geodata)
cri = gadm("Costa Rica", level=1, path=".")

# fake "ecoregions" data
ecoregions <- as.polygons(rast())

x <- crop(r, cri)
plot(x)