Dear all,

It will probably be a very stupid thing I do, but I am trying to calculate
residence 'times' for a binary raster (1,0) and found the error

Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) :
  cannot use this function


Maybe there are other ways of doing it , but so far, for vectors, I used
rle to calculate the repetitions of the same value across a sequence. I was
hoping I could use it for raster too. On trying it 'cell-by-cell' I could
do it. However, this is a very large raster and I guess that even mcapply
would take a while. I was wondering if there is a neat code, or other
package that I could use.

Any help would be greatly welcome,

Kind regards,

JM

### See code below for toy example


#INPUT LAYERS
time1 <- raster(matrix  (c(1,1,0,1,0,0,0,0,0),nrow=3))
time2 <-  raster(matrix (c(1,1,0,0,0,1,0,0,0),nrow=3))
time3 <-  raster(matrix (c(0,1,0,1,0,1,0,1,0),nrow=3))
time4 <-  raster(matrix (c(1,1,1,1,0,1,0,1,0),nrow=3))

#expected results for Max. residence (e.g. How many many
times,sequentially, number 1 appears)
r <-  raster(matrix (c(2,4,1,2,0,3,0,3,0),nrow=3))

#raster stack
s<-stack(time1,time2,time3,time4)

s.test1 <- calc (s , fun=function (x){
    count.trends <- rle(as.vector(x))
    res.times <- count.trends$lengths[which(count.trends$values==1)]
    res.times.max <- max(res.times)
    res.times.ave <- mean(res.times)
    res.times.var <- var(res.times)
    res.times.slp <- coef(lm(res.times~seq(1:length(res.times))))[2]
            return(res.times.max)
            return(res.times.ave)
            return(res.times.var)
            return(res.times.slp)
    }#end function
) #end calc


#if I convert the values of each cell to a vector first, I can do it. I
could go through mclapply, but it is a large raster anyways

test.per.cell <-function (s=s,cell){
          count.trends <- rle(as.vector(s[cell]))
          res.times <- count.trends$lengths[which(count.trends$values==1)]

            #make calculations
            res.times.max <- max(res.times)
            res.times.ave <- mean(res.times)
            res.times.var <- var(res.times)
            res.times.slp <-
as.numeric(coef(lm(res.times~seq(1:length(res.times))))[2])

            #return results
            return (res.times.max )
            return (res.times.ave )
            return (res.times.var )
            return (res.times.var )
}

	[[alternative HTML version deleted]]

