I downloaded this shapefile from here
https://data.apps.fao.org/catalog/iso/7707086d-af3c-41cc-8aa5-323d8609b2d1
I read it like this:
library(sf);library(terra); library(exactextractr)
file <- st_read("~\\Major_hydrobasins.shp")
and then select:
aoi=subset(file, file$MAJ_NAME == "Narmada")
When I plot aoi, I see one polygon, but when I look at the features of aoi, I see 6 features.
Now if I want to compute the mean of raster a over the polygon only aoi, I get 6 values
a <- rast(ncols=40, nrows=40, xmin=-180, xmax=180, ymin=-40, ymax=60,
crs="+proj=longlat +datum=WGS84")
values(a) <- 1:ncell(a)
exactextractr::exact_extract(a, aoi, "mean")
The question is: how do I merge these 6 features into only one polygon?
You can use terra
with exactextractr
package to achieve this like
library(terra); library(exactextractr)
file <- vect("Major_hydrobasins.shp")
aoi = subset(file, file$MAJ_NAME == "Narmada")
##Dissolve the SpatVector to combine all geometries into one geometry
va <- aggregate(aoi, "MAJ_NAME")
a <- rast(ncols=40, nrows=40, xmin=-180, xmax=180, ymin=-40, ymax=60,
crs="+proj=longlat +datum=WGS84")
values(a) <- 1:ncell(a)
exactextractr::exact_extract(a, st_as_sf(va), "mean")
Which returns me only one value 611.5938
If you save it as shapefile and open it in QGIS, you can see that except 6th polygon others are very small polygons outside the basin