0

I am trying to crop and mask raster data and convert the raster data to a vector and to an sf object with terra. However, I always get the following error message: Error in UseMethod ("st_as_sf") not applicable method for 'st_as_sf' applied to object of class "SpatVector". I would appreciate any help or advice to overcome this hurdle.

My code looks as follows

packs <- list("sf", "tidyverse", "terra")
lapply(packs, require, character.only=TRUE)

pop_count <- rast(raster.path)
adm_ner_sf <- st_read(shp.path)

pop_afg_sf <- pop_count %>%
  crop(vect(adm_afg_sf)) %>%
  mask(vect(adm_afg_sf)) %>%
  as.points() %>%
  st_as_sf() %>%
  rename(pop_count = gpw_v4_population_count_rev11_2010_2pt5_min)

I am using SEDAC population density raster data (Formal class SpatRaster), which I am trying to limit to the shape of Afghanistan, by using an Afghanistan shape file (adm_afg_sf).

Any feedback would be greatly appeciated.

EsmaeelE
  • 2,331
  • 6
  • 22
  • 31
Penny
  • 1

1 Answers1

0

I think what you do is as equivalent to the minimal self-contained reproducible example below and that works:

library(terra)
library(sf)

f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)
p <- as.points(r)
s <- st_as_sf(p)

Perhaps you have old versions of sf and/or terra? Try update.packages()

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63