I have a multiple band raster and want to calculate cumulative sums of each pixel throughout the bands. The bands include NA pixels at varying locations and the cumsum function in calc from the raster package writes NA in subsequent bands if it encounters a NA value in a pixel. Finally I have only NA pixels left in the last cumulative sum band. I changed NA to zero, but that leads to an underestimation of the values.
Is it possible to use the preliminary value to NA? Or maybe even an average of the preliminary and the following value?
library(raster)
raster <- stack("inputPath")
cumulative_sum <- calc(raster, cumsum)
here is an example of what I mean
input band 1
1 4 7
NA 5 8
3 6 NA
input band 2
2 NA NA
3 6 9
4 7 10
input band 3
1 4 7
2 5 8
3 6 9
result with calc and cumsum
4 NA NA
NA 16 25
10 19 NA
desired output (last resulting band <- band1 + band2+ band3)
4 12 21
5 16 25
10 19 19
na.locf()
(zoo
package) is what you're looking for. This fills NA's with the last observed value after which you can use cumsum as normal. – Niek