0

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.
}
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
Lily Nature
  • 613
  • 7
  • 18
  • You say "This does not work for me, gives output as zero." But it clearly works in the example., – Robert Hijmans Mar 27 '18 at 20:43
  • Yes it works for this example however for large data set ( about 100 it runs for few hours and give me output that has all zero value. I could not figure out why i am getting such error. Thank you. – Lily Nature Mar 28 '18 at 16:42

1 Answers1

1

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'))
}
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63