Search code examples
rraster

Calculating julian day based on degree day using calc() function


I wrote the following function to obtain an earliest julian day with cumulative degree day exceeding GDD.

## data
s <- stack(list.files("daily_Temperature"))

## myfun() function
myfun <- function(x, start, GDD) {
 i <- start
  repeat{
   if(sum(x[start:i], na.rm=T) >= GDD) {break}
   i <- i+1
  }
  i
 }

## calc() function
start <- raster("Raster_contains_certain_julian_dates.tif") #same resolution&extend
calc(s, fun=myfun)

When I run myfun() with simple vector, it works.

v <- c(10, 13, 15, 14, 16)
myfun(x=v, start=1, GDD=40)

But when I use myfun() in calc() function, console returns some error.

cannot use this function

How can I make this work with s using calc()?


Solution

  • Here is a proposal. When working with a raster as a parameter of a calc function, you should add it at the end of your stack to be able to call it in the function.

    Function

    ## myfun() function
    myfun <- function(x) {
      start <- x[n] 
      i <- 0
      while (i < n){
        if(sum(x[start:i], na.rm=T) >= GDD) {break}
        i <- i+1
      }
      if (i == n){NA}else{i}
    }
    

    Code

    s <- stack(r1,r2,r3,r4,r5,start)
    n <- nlayers(s)
    GDD <- 40
    output <- calc(s, fun = myfun)
    
    plot(output)
    

    enter image description here

    Sample data

    library(raster)
    
    set.seed(1)
    # Generate rasters of random values
    r1 <- r2 <- r3 <- r4 <- r5 <- start <- raster(ncol=10, nrow=10)
    
    r1[] <- round(runif(ncell(r1), 5, 15))
    r2[] <- round(runif(ncell(r2), 5, 15))
    r3[] <- round(runif(ncell(r3), 5, 15))
    r4[] <- round(runif(ncell(r4), 5, 15))
    r5[] <- round(runif(ncell(r5), 5, 15))
    s <- stack(r1,r2,r3,r4,r5)
    
    start[] <- round(runif(ncell(start), 1, 3))