0

I have a water shapefile from this website: https://geodata.lib.utexas.edu/catalog/stanford-ws441bn8045

library(terra)
library(rgdal)
library(tidyverse)
library(raster)
library(sf) 
library(sp)
library(spData)
library(exactextractr)
library(tmap)
library(tidycensus)



x <- read_sf("bayarea_majorwater.shp")

Now I only want a part of that using bbox

enter image description here

e <- ext(c(5568137, 6156695, 1836155, 2431425))
wa <- crop(x, e)

But when I doing this it says inherited method

Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘crop’ for signature ‘"sf"’

Is there a way to say that you want only a part of the spatial extent of the shaepfile?

2
  • It says "inherited method"? Does it say anything else? Can you show the full error message? That always helps. You should also say which packages you've attached with "library" calls, because the ext and crop functions could be coming from anywhere...
    – Spacedman
    Dec 13, 2022 at 16:26
  • I edited it, but I get the same error when doing terra::crop()
    – user215748
    Dec 13, 2022 at 16:36

1 Answer 1

1

When you see this error:

Error in (function (classes, fdef, mtable) : 
unable to find an inherited method for
function ‘crop’ for signature ‘"sf"’

it means you are trying to call crop with an argument it was not built to understand. What does it understand? Check the help(crop):

Description:

     Cut out a part of a SpatRaster with a SpatExtent, or another
     object from which an extent can be obtained.

But you don't have a SpatRaster you have an sf spatial data frame.

The functions to work with sf data nearly all start with st_ and live in the sf package. help.search("crop") shows us:

sf::st_crop             crop an sf object to a specific rectangle
  Aliases: st_crop, st_crop.sfc, st_crop.sf

There's various ways to pass the coordinates of the crop including specifying each one as an argument, eg:

> xc = st_crop(x, xmin=500000, ymin=4140000, xmax=600000, ymax=4240000)
Warning message:
attribute variables are assumed to be spatially constant throughout all geometries

and I can plot that over the full data:

> plot(x$geometry) 
> plot(xc$geometry, add=TRUE, col="red")

enter image description here

and you can see how it has cut out the square (although you can't see the top and right edges of the square, it has cut the ring on the far right).

Note your coordinates are not in the range of the data, so maybe they are in the wrong coordinate system for this map. You need to supply the crop coordinates in the same coordinate system as the map data, so maybe you need to use st_transform to get them correctly. But that's another question...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.