I have a multiband raster of the Arctic showing the day of the year on which snow melts. I have grid cell values that equal 0 but they should be 365 as the snow never melts. I have tried to use the raster calculator to set all the grid values that were 0 to 365:

("arctic@1" = 0) * "arctic@1"

, but this only gives me a true or false raster. I want it to be conditional, if "arctic@1" = 0 then 365 else "arctic@1".

I also visited this advice, and it gave me values of 1.78e+308 and -1.78e+308 which is also wrong.

How can I perform a conditional statement in which I change the 0's with 365's for a multiband raster? I can do this in Qgis or R, but do not know how to perform it in the latter.

1 Answer 1


For layer 2 of a layer called zeroes, this expression will replace zeroes with 365, and leave the rest unchanged:

 365*("zeroes@2" = 0) + "zeroes@2" * ("zeroes@2" != 0)

Comparisons with = return False if not equal, which is numerically interpreted as 0. The first part (before +) is then a raster of 365 where there is zero, and zero elsewhere, and the second part (after +) is a raster of the zeroes@2 values unless its zero in which case its zero. Oh, that can be simplified (not tested):

 365*("zeroes@2" = 0) + "zeroes@2"

So that first part is 0 or 365 only, and then you add the layer back in again, and since 0+0 = 0 you end up with 365 where there was zero, and the original layer value elsewhere.

I can only see how to do this one layer at a time with the raster calculator though - maybe there's a way...

In R, starting with a stack s, you can replace values conditionally:

> z = s
> z[z==0]=365

and comparing z with what we started with you can see the zeroes are now 365s@

> table(z[])

  1   2   3   4 365 
  6  11   8   8   3 
> table(s[])

 0  1  2  3  4 
 3  6 11  8  8 
  • 1
    Listen, you solved my week-old problem, I am eternally grateful!
    – Thomas
    Commented Jun 7, 2021 at 12:43

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.