jeudi 24 juin 2021

Applying a conditional sum on rasterstack in Rstudio

We are trying to sum up raster values in a stack based on a condition. The stack contains raster data (Values are just 1 or 0) from different time steps. We are trying to sum up the stack, with the condition that if a Zero appears in one pixel it is summed up again from Zero and ignoring what was befor. We want to do that pixelwise but end up getting the error below. The following Code is just an Example data set to give you an example:

r1 <- raster(ncol=100,nrow=100)
r2 <- raster(ncol=100,nrow=100)
r3 <- raster(ncol=100,nrow=100)
r4 <- raster(ncol=100,nrow=100)
r5 <- raster(ncol=100,nrow=100)


r1[] <- round(runif(n=ncell(r1), min=0, max = 1))
r2[] <- round(runif(n=ncell(r1), min=0, max = 1))
r3[] <- round(runif(n=ncell(r1), min=0, max = 1))
r4[] <- round(runif(n=ncell(r1), min=0, max = 1))
r5[] <- round(runif(n=ncell(r1), min=0, max = 1))

jj <- stack(r1, r2, r3, r4, r5)


Fun_Duration <- function(ff) {
  g <- brick()
  g <- addLayer(g, ff[[1]])
  
  for (i in 2:nlayers(ff)) {
    j <- overlay(ff, g, fun = function(ff, g){
      ifelse(g[[i-1]] == 0, 0 + ff[[i]], g[[i-1]]+ff[[i]])})
    g <- addLayer(g, j)
  }
  return(g)
}


b <- Fun_Duration(jj)

b <- overlay(jj, fun = Fun_Duration)

we are getting following Error:

Error in .overlayList(x, fun = fun, filename = filename, forcefun = forcefun, : cannot use this formula, probably because it is not vectorized

Thanks for the help.

Aucun commentaire:

Enregistrer un commentaire