Getting error in calculation of mean for tiff file by using calc function

rraster

I have a 4 raster tiff files and I want to calculate the mean of it. I am using the "calc" funtion for it. My code is following .

    library(raster)
    fs <- list.files(path="directory", pattern = "tif$", full.names = TRUE)
    s <- raster::stack(fs)
    s1 <- calc(s, mean)

Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘calc’ for signature ‘"RasterStack", "RasterLayer"

It give me this error but If I use sd (standard deviation)instead of mean it give me result but not working for mean.

I don't know what's going on with mean calculation.

Could anybody explain it for me?

Best Answer

Reading the error message:

Error in (function (classes, fdef, mtable) : unable to find an inherited 
method for function ‘calc’ for signature ‘"RasterStack", "RasterLayer"

the "signature" is telling me the first argument is a RasterStack but the second argument is a RasterLayer. That means "mean" is a RasterLayer. Do you have a RasterLayer called "mean"? That would be overriding the "mean" function. I can replicate your error this way. First it works:

> m = matrix(1:12,3,4)
> r = raster(m)
> s = stack(list(r,r,r))
> mm = calc(s, mean)
>

Then I make a raster called "mean":

> mean = r
> mm = calc(s, mean)
Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘calc’ for signature ‘"RasterStack", "RasterLayer"’

Fix either by removing the "mean" raster, or using base::mean to get the right mean function:

> mm = calc(s, base::mean)
>