3

I am using the following code to extract mean pixel values over an area represented by a polygon:

mean<-lapply(S2_stack, FUN=function (S2_stack) {data.frame(mean=extract(S2_stack, polygons2, fun=mean))})

Where:

> S2_stack
class      : RasterStack 
dimensions : 1454, 1595, 2319130, 4  (nrow, ncol, ncell, nlayers)
resolution : 10, 10  (x, y)
extent     : 744490, 760440, 4773400, 4787940  (xmin, xmax, ymin, ymax)
crs        : +proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 
names      : Subset_S2_MSIL2A_20180511T100029_MCI, Subset_S2_MSIL2A_20180710T100029_MCI, Subset_S2_MSIL2A_20180906T101021_MCI, Subset_S2_MSIL2A_20181115T101251_MCI 

and polygons2:

polygons2 <- readOGR('/path/Insitu_poly.shp')

with:

> class(polygons2)
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"

When I try to run my code I am getting the following error:

 Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ?extract? for signature ?"numeric", "SpatialPolygonsDataFrame"?

Not sure why. It seems extract needs a SpatialPolygonsDataFrame and as far as I know, it should run

Any idea?

  • @Aaron same error using mean<-lapply(S2_stack, FUN=function (S2_stack) {data.frame(mean=raster::extract(S2_stack, polygons2, fun=mean))}) Not sure how to proceed. Chekcint the documentation, I dont see a problem in the class of polygons2 – GCGM Feb 26 at 15:20
  • 3
    Use simply extract(S2_stack, polygons2, fun=mean, df = T). Don't use lapply – aldo_tapia Feb 26 at 15:31
  • 1
    I think the problem is with the raster, not the polygons. I've never used lapply when extracting from a raster stack. Maybe try just doing mean <- extract(S2_stack, polygons2, fun=mean) – Nick Feb 26 at 15:40
  • 1
    Your stack has four bands. Do you want the average in each band separately? Or over all bands? lapply(1:4, FUN=function (i) {raster::extract(S2_stack[[i]], polygons2, fun=mean)}) maybe? – Spacedman Feb 26 at 16:32
  • Using the code without lapply worked. However, I do not get completley why as I am providing a list (of rasters) and a funciton to be applied. Please add the comment as an answer and I ll be glad to accept it. – GCGM Mar 2 at 10:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.