I would like to count number of layers in a stack with value equal to raster pixel value. Here is my current try:

r1 <- calc(s, fun=function(x){sum(x == r)})

I get two errors

Error in FUN(newX[, i], ...) : unused argument (na.rm = TRUE)


Error: cannot allocate vector of size 1.9 Mb

Where I'm going wrong?

  • how is r defined?
    – obrl_soil
    Dec 11, 2018 at 9:49
  • r is a raster file while s is a raster stack @obrl_soil
    – jmutua
    Dec 11, 2018 at 11:12

1 Answer 1


Yeah ok, raster::calc() only operates on a single object, so your formula is essentially trying to total up all the occasions where one of your stack's cells equals a whole raster, which is never.

Try this: first, stack r and s. This means each pixel in the output stack becomes a vector where element 1 is the reference value and the rest are comparison values. Then run calc on that object, with a function like

function(x) {
  comp <- x[1]
  main <- x[2:length(x)]
  length(main[main == comp])

This should return a raster where each cell is a count of how many stack layers equal the overlying reference cell value.

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.