rar - 1 year ago 155

R Question

I need to compute number of three consecutive days when value of each pixel in a raster stack (

`x`

`y`

`rle`

`calc`

`x`

`y`

`a`

`library(raster)`

fn<-function(a) with(rle(a), sum(lengths>=3 & values>a[[nlayers(a)]]))

calc(b,fn)

However, I am getting the error:

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

cannot use this function

Reproducible sample:

`x1 <- raster(nrows=10, ncols=10)`

x2=x3=x4=x5=x6=x1

x1[]= runif(ncell(x1))

x2[]= runif(ncell(x1))

x3[]= runif(ncell(x1))

x4[]= runif(ncell(x1))

x5[]= runif(ncell(x1))

x6[]= runif(ncell(x1))

x=stack(x1,x2,x3,x4,x5,x6)

y=x1

y[]= runif(ncell(x1))

a<-stack(x,y)

Can someone please help.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You could try this:

```
x1 <- raster(nrows=10, ncols=10)
x2=x3=x4=x5=x6=x1
x1[]= runif(ncell(x1))
x2[]= runif(ncell(x1))
x3[]= runif(ncell(x1))
x4[]= runif(ncell(x1))
x5[]= runif(ncell(x1))
x6[]= runif(ncell(x1))
x=stack(x1,x2,x3,x4,x5,x6)*4
y=x1
y[]= runif(ncell(x1))*2
a<-stack(x,y)
library(raster)
fn<-function(x) {
seq <- rle(as.numeric(x)>as.numeric(x)[[nlayers(a)]])
n = length(seq$lengths > 3 & seq$values == TRUE)
return(n)
}
calc(a,fn)
class : RasterLayer
dimensions : 10, 10, 100 (nrow, ncol, ncell)
resolution : 36, 18 (x, y)
extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
data source : in memory
names : layer
values : 1, 7 (min, max)
```

(note that I modified the example dataset to get some good sequences)

HTH !

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**