[R-sig-Geo] Extract Raster Data Values to Shapefile

Julien Rodriguez ju||enrodr|guez@@rd@@pm @end|ng |rom gm@||@com
Wed May 11 19:52:28 CEST 2022


Hi Luca and Zivan,


Maybe this toy example using terra and sf (probably the class of your
district borders object) may help.

library(terra)
library(sf)

# Create a SpatRaster
r <- rast(ncols=5, nrows=5, xmin=0, xmax=5, ymin=0, ymax=5)
values(r) <- 1:25

# Create a polygon object as sf
p1 <- rbind(c(1, 1), c(3, 1), c(3, 3), c(1, 3), c(1, 1))
p2 <- rbind(c(4, 0), c(4, 1), c(5, 1), c(5, 0), c(4, 0))
myPol <- st_sf(code = c(1:2), geometry = st_sfc(list(st_polygon(list(p1)),
st_polygon(list(p2)))))

# Polygon object as SpatVector
myPolAsSpatVect <- vect(st_geometry(myPol))

plot(r)
plot(myPolAsSpatVect, add = TRUE)

# Here is your extraction, using fun argument, you can decide how to
aggregate the values by district border
terra::extract(r, myPolAsSpatVect, fun = mean)

Regards

Julien




Le mer. 11 mai 2022 à 18:19, Zivan Karaman <zivan.karaman using gmail.com> a
écrit :

> Hi Luca,
> You should perhaps have a look at the crop and mask function in the raster
> or terra package.
> Hope this helps!
> Zivan
>
> On Wed, May 11, 2022 at 6:09 PM <lucfrank using mail.uni-mannheim.de> wrote:
>
> > Hello Everyone,
> >
> > I have a shapefile with district borders and a raster data file (.tif).
> >
> > How can I extract the value from the raster data onto each district in
> > the shapefile?
> >
> > I have the exact thing I want with two shapefiles with the command:
> >
> > x <- st_join(x,y,join=st_overlaps,left=TRUE,largest=TRUE)
> >
> > This gives me the result I want. I tried to convert the .tif file to a
> > shapefile, but this didn't work for me with multiple different
> > solutions I found online.
> >
> > I would appreciate any ideas you might have.
> >
> > Luca
> >
> > _______________________________________________
> > R-sig-Geo mailing list
> > R-sig-Geo using r-project.org
> > https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> >
>
>         [[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo using r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list