Search code examples
rrastercalc

Function raise error with return statement


I want to process a own designed function on every cell using the calc function of the "raster" package.

Everything works perfectly when I try to print the "final" result of the function (value I want to return), but when I try to use return statement, I got an error :

Error in .local(x, values, ...) : 
  values must be numeric, integer or logical.

Here is the code leading to that error

inR <- 'D://test/TS_combined_clipped.tif'
outR <- 'D://test/R_test3.tif'

rasterB <- brick(inR)
fun1 <-function(x){
  years = seq(1, 345)
  na_idx = which(is.na(x))
  years = years[-na_idx]
  x <- na.omit(x)
  idx = detectChangePoint(x, cpmType='Student', ARL0=500)$changePoint
  return(years[idx]) # this raises error
  # print(years[idx]) # This does *not* raises any error
}

r <- calc(rasterB, fun=fun1, filename=outR, overwrite=TRUE)

How is it possible to have a return statement to make it fails ?

Some of my tests leads to the fact that it seems that the process fails just after the execution of the calc function on the very last cell of the rasterBrick. But I have no clue of where to start to try to fix this.

Input image is available here

[EDIT]

I just noticed that if I use return(idx) instead of return(year[idx]) the process works without error raised. So it seems that the problem is more at fetching the value of the year variable. Is therefore any particular thing that I missed in the use of indexes with R ?


Solution

  • Comment of user2554330 put me on the good track, issue was that calc cannot handle a "numeric(0)" result.

    Updated code is then

    inR <- 'D://test/TS_combined_clipped.tif'
    outR <- 'D://test/R_test3.tif'
    
    rasterB <- brick(inR)
    fun1 <-function(x){
      years = seq(1, 345)
      na_idx = which(is.na(x))
      years = years[-na_idx]
      x <- na.omit(x)
      idx = detectChangePoint(x, cpmType='Student', ARL0=500)$changePoint
      if (idx==0){
        return(0)
      } else {
        return(as.integer(years[idx]))
      }
    }
    
    r <- calc(rasterB, fun=fun1, filename=outR, overwrite=TRUE)