# Receiving higher values than should be possible in stackApply SUM for Frequency calculation in R

I am currently working on creating a frequency raster for a country based on multiple Rasters of the same day through following years and where the previous values are reclassified to 1's and 0's. The RasterStack is then SUMMED together to create the final frequency output. I am getting an output, but the problem is that the max value is too high.

For example, if I have 16 rasters in the stack, then the highest possible value should be 16 but instead I am getting a max value of 39. Below is the script I have created.

``````library(raster)

cloudstack <- stack(flsp) #Creation of RasterStack, 16 Rasters

m <- c(-Inf, 2, 0,  3, 3, 1,  4, Inf, 0) #Cloud = 1, Everything else = 0
reclassmatrix <- matrix(m, ncol=3, byrow=TRUE)
reclass <- reclassify(cloudstack, reclassmatrix) #Reclassify RasterStack

#SUM RasterStack
cloud_frequency <-stackApply(reclass,
indices=c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1), fun=sum, na.rm=TRUE)

crop_cloud <- crop(cloud_frequency, country)
``````

Please provide a reproducible example.

Perhaps this is because there are values in between 2 and 3 and 3 and 4?

To sum the layers you should do `sum(reclass)`

``````library(raster)
s <- stack(system.file("external/rlogo.grd", package="raster"))
s <- stack(s, s, s)
ss <- reclassify(s, matrix(c(-Inf, 254, 0, 254, 255, 1), ncol=3, byrow=TRUE))
sum(ss)
# more direct than
# stackApply(ss, indices=rep(1, nlayers(ss)), fun=sum)
``````