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?
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 ofpolygons2
extract(S2_stack, polygons2, fun=mean, df = T)
. Don't uselapply
mean <- extract(S2_stack, polygons2, fun=mean)
lapply(1:4, FUN=function (i) {raster::extract(S2_stack[[i]], polygons2, fun=mean)})
maybe?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.