I have one raster file on land cover (30x30m pixels), one raster file on soil organic carbon (SOC) (250x250m pixels), and one vector file with contiguous polygons of different sizes.

What I require is a mean SOC value for each polygon, based on pixels whose landcover includes at least 60% grassland.

Here is a related post: Extracting values from one raster based on condition in another raster and distinguished by polygons in a vector file which works really well. I am uncertain how to adjust this conditional statement (1) ifel(lulc == 3, 1, NA) to only consider pixels with a minimum amount (%) of grassland.

The current code only distinguishes whether a cell is grassland or not. That means, grassland may only account for a small amount of the land use in the cell. The carbon value allocated to the cell is based on dominant land use, however, which could be annual cropland or forest, with quite different SOC values compared to actual grassland.

Here is an example code, that was earlier suggested by @JeffreyEvans (for details see aforementioned link):


polys <- st_read(system.file("shape/nc.shp", package="sf"))
  polys <- st_transform(polys, crs="ESRI:102008")

lulc <- rast(ext(polys), resolution = 1000)
  lulc[] <- sample(1:4, ncell(lulc), replace=TRUE) 
soc <- rast(ext(polys), resolution = 1000)
  soc[] <- sample(seq(0.5,3,0.01), ncell(soc), replace=TRUE) 

plot(c(lulc, soc))

grass <- ifel(lulc == 3, 1, NA)
  grass.soc <- mask(soc, grass)
    plot(grass.soc, col="black",legend=FALSE)

mean.soc <- extract(c(soc,grass.soc), vect(polys), 
           fun=function(x) {mean(x,na.rm=TRUE)})
  names(mean.soc) <- c("ID","SOC","GRASS_SOC")  
polys$soc <- mean.soc[,2]
polys$grass.soc <- mean.soc[,3]

Just to add. Because in my actual research problem the two rasters have different pixel sizes, I had to first unify their dimensions and resolutions, for which I used code like:

g <- terra::resample(soc,lulc, method = 'near')


Your Answer

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

Browse other questions tagged or ask your own question.