Search code examples
rloopslayerraster

R Raster - Create layer with conditionals looping through multiple layers


I am working with a time-series raster brick. The brick has 365 layers representing a value for each day of the year.

I want to create a new layer in which each cell holds the number of day of year in which a certain condition is met.

My current approach is the following (APHRO being the raster brick), but returns the error message below:

enter code here
r <- raster(ncol=40, nrow=20)
r[] <- rnorm(n=ncell(r))
APHRO <- brick(x=c(r, r*2, r))    
NewLayer <- calc(APHRO, fun=FindOnsetDate(APHRO))

Returning this error:

 Error in .local(x, ...) : not a valid subset 

And the function being parsed:

FindOnsetDate <- function (s) {
  x=0  
  repeat {
    x+1
    if(s[[x]] >= 20 | s[[x]] + s[[x+1]] >= 20 & ChkFalseOnset() == FALSE)
    {break}
  }
  return(x);
}

With the function for the 3rd condition being:

ChkFalseOnset <- function (x) {



  for (i in 0:13){

    if (sum(APHRO[[x+i:x+i+7]]) >= 5)
    {return(FALSE); break}
    return(TRUE)  
  }
}

Thank you in advance!!!!

And please let me know if I should provide more information - tried to keep it parsimonious.


Solution

  • The problem is that your function is no good:

    FindOnsetDate <- function (s) {
       x=0  
       repeat {
         x+1
         if(s[[x]] >= 20 | s[[x]] + s[[x+1]] >= 20)
         {break}
       }
       return(x);
     }
     FindOnsetDate(1:100)
     #Error in s[[x]] : 
     # attempt to select less than one element in get1index <real>
    

    Perhaps something like this:

    FindOnsetDate <- function (s) {
       j <- s + c(s[-1], 0)
       sum(j > 20 | s > 20)
       # if all values are positive, just do sum(j > 20)
    }
    FindOnsetDate(1:20)
    #10
    

    This works now:

     r <- calc(APHRO, FindOnsetDate)