0

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?

1 Answer 1

3

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)
> 
4
  • Thanks for your detailed reply. The thing is what I felt after your comment is these 4 tiff files are actually stack of multiple files. I took the mean and made these 4 files from 5-5 separate files after taking their mean. Secondly, files name has no 'mean' word in it _Spacedman.
    – user_3264
    Commented Dec 2, 2021 at 8:23
  • 1
    I don't understand. Does your code work with your data if you use base::mean instead of just mean? If so then you've got an object called "mean" in your search path that is breaking calc.
    – Spacedman
    Commented Dec 2, 2021 at 8:40
  • @user_3264 it doesn't matter that there's no "mean" in the 4 files you read in. There's an object called "mean" somewhere that is getting used instead of R's "mean" function. Maybe you created it yesterday, or a week ago, or its been reloaded from R's saved .RData. But it must be there. If I'm right please accept the answer.
    – Spacedman
    Commented Dec 2, 2021 at 9:23
  • Yes thank you so much for detailed guidance again. I accept the answer.
    – user_3264
    Commented Dec 2, 2021 at 9:30

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.