R – Unable to Sum Raster Files Using Raster Package

rraster-calculatorrgdal

I am trying to sum all of my raster files (over 500) from a single folder in R, using the raster package, but am encountering an error message I cannot figure out how to solve. I am trying to use to use this package to use the raster calculator to sum these files.

I have a folder of raster images (.tif). I then run the following code in R.

library(rgdal)
library(raster)

allrasters <- stack(list.files('C:/Users/MyName/Path/to/My/Data/Folder', full.names=T)

raster_sum <- calc(allrasters, fun=sum,na.rm=T, ,filename='C:/Users/MyName/Path/to/Outputs/Folder/Raster_Sum_Output.tif')

which yields the following error message:

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

What might be the cause for this, and how can I fix this problem so that I can get my intended output raster which is the sum of all the raster files in my folder? have not been able to find online how I might address this issue, since the the "RasterStack" and "numeric" components are too specific.

Best Answer

Have you got a numeric object called sum?

> sum=99
> raster_sum <- calc(allrasters, fun=sum,na.rm=TRUE)
Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘calc’ for signature ‘"RasterStack", "numeric"’

The error is saying you are calling calc with a RasterLayer and a numeric argument, so the second argument must be numeric, and not a function. Remove any sum numeric object, or do base::sum:

> raster_sum <- calc(allrasters, base::sum, na.rm=TRUE)
> 

(Oh and always spell TRUE out because that can break stuff too...)