Search code examples
rrasterr-raster

looping through large rasterbrick in raster R


How can i perform for-loop in a large daily rasterbrick to get annual stacks and calculate the maximum value (annual maxima ) for each year( each stack of 365 files). Basically, i have same question like this. So taking same question as sample, how i can conduct a for-loop that would calculate maximum value for each 46 stacks ( each stack with 8 layers). I tried using only stackApply but it gives all black/zero value when i run for whole period, however it gives max values if i run for individual years (tested separately for 10 years, i have more than 100 years data).

library(raster)
# example data
sca <- brick(nrow=108,ncol=132,nl=365) 
values(sca) <- runif(ncell(sca)*nlayers(sca))

# indices grouping sets of 8
i <- rep(1:ceiling(365/8), each=8)
# the last period is not a complete set of 8 days
i <- i[1:nlayers(sca)]
# This does not work for me, gives output as zero.
x <- stackApply(sca, i, max)

for (i in 1:nlayers(sca)) {
  x <- sca[[i]]
  xx<-stackApply(sca, i, max)
  plot(xx)
  # etc.
}

Solution

  • You could loop like this:

    library(raster)
    sca <- brick(nrow=108,ncol=132,nl=365) 
    values(sca) <- runif(ncell(sca)*nlayers(sca))
    
    i <- rep(1:ceiling(365/8), each=8)
    i <- i[1:nlayers(sca)]
    
    for (j in unique(i)) {
      x <- sca[[which(j==i)]]
      xx <- max(x, na.rm=TRUE)
      # or
      # xx <- calc(x, fun=max, na.rm=TRUE, filename = patste0(i, '.tif'))
    }