# Sum multiple raster layer under condition

For a suitability analysis I need to sum up three raster layers `a,b,c`considering different conditions. let's say, output layer is `d`.

I'd prefer Open Source Software, particularly QGIS (with SAGA, GRASS, R extension)

All three layers have the cell values: NoData; 1 (noGo); 2 (very bad); 3 (critical); 4 (good); 5 (mustGo).

I have the following conditions:

``````if a=1 OR b=1 or c=1 then d=1
if a=5 OR b=5 or c=5 then d=5
else d=(a+b+c)/("number of raster with value between 2 and 4")
``````

e.g:

``````a=2, b=4, c=1 --> d=1
a=5, b=4, c=2 --> d=5
a=5, b=4, c=3 --> d=(5+4+3)/(1+1+1)=4
a=4, b=4, c=NoData --> d= (4+4)/(1+1)=4
``````

With SAGA GIS Raster Calculator, this formula worked:

``````ifelse(eq(a,1),1,
ifelse(eq(b,1),1,
ifelse(eq(c,1),1,
ifelse(eq(a,5),5,
ifelse(eq(b,5),5,
ifelse(eq(c,5),5(a+b+c)/)ifelse(a>0,ifelse(a<5,1,0),0)+ifelse(b>0,ifelse(b<5,1,0),0)+ifelse(c>0,ifelse(c<5,1,0),0
))))))))
``````

## But:

Is there any way, for a better/cleaner formula? This one is so clumpy. I could also do `0` instead of `NoData`.

## Update:

I've just realized, that the formula doesn't work properly. As you can see here: The `NoData`value in raster a curtains the calculation to the lines (roads) which have values in raster `a`.Actually, I'd expect `(3+2)/(1+1)=3.5`here. (I took a cell somewhere in the black area)