0

I have 12 binary (raster) files . I would like to calculate the moving average for the 12 values for each pixel in the 12 files.

For a simple vector we can get a moving average by using this :

         x <- c(1,2,3,NA,NA,4,6,5,6,4,2,5)
        movingmean <- rollapply(x, 3, FUN = mean, na.rm = T,fill=NA)

now I want to do the same but with rasters and I tried:

files   <- list.files("C:final-2010", "*.envi", full.names = TRUE)
results <- list()
for (.files in files) {
    # read in the 12 files as a vector of numbers 
    # that we take the average of
    x <- do.call(rbind,(lapply(.files, readBin  , double() , 
                     size = 4 ,n =1440 * 720 , signed = T)))
    # take the moving average across the 12 values 
    # from the 12 files for each pixel
    results[[length(results) + 1L]] <- rollapply(x, 3, FUN = mean,na.rm = T)
}

But got this error:

    Error in seq.default(start.at, NROW(data), by = by) : 
                             wrong sign in 'by' argument
Barry
  • 739
  • 1
  • 8
  • 29

1 Answers1

1

Maybe something like this will work

results <- overlay(stack(files), fun=function(x) 
                   movingFun(x, fun=mean, n=3, na.rm=TRUE))
Jesse Anderson
  • 4,507
  • 26
  • 36
  • 1
    Well I assume @RobertH is Robert Hijmans and he wrote the `raster` package you are using so is intimately familiar with what the code does! Look at the default arguments of `movingFun`. You are going to return 12 rasters. The first will average the values of rasters -1,1,2, then 1,2,3, ending at 11,12,13. Since -1 and 13 don't exist these values will be `NA`, but we have `na.rm=TRUE` which means that the first and last will be averages of rasters 1 & 2 and 11 & 12 respectively. If you want something different read the docs! – Simon O'Hanlon Feb 19 '13 at 15:08