0

How can i create a rasterbrick rdt from rasterbrick r so that rdt show the day of the year on which the grid cell value is greater than or equal to 0.75 in the following example. library(raster)

# Create a raster

r1 <- raster(nrow=10, ncol=7)
r <- stack(setValues(r1, runif(ncell(r1))),
           setValues(r1, runif(70 ,0.6,0.9)),
           setValues(r1, runif(70 ,0.2,0.4)),
           setValues(r1, runif(70 ,1,2)),
           setValues(r1, runif(70 ,0.5,1.0)),
           setValues(r1, runif(70 ,0.3,0.9)),
           setValues(r1, runif(70 ,1,2)))
r

# Make Dates. This is random, i have about 24000 values.

Dates<-data.frame(Date=c("2000-01-02","2000-01-03","2000-02-03",
                         "2001-09-02","2001-09-03","2001-10-01",
                         "2001-10-02"))

Date_val<-as.Date(Dates$Date,format="%Y-%m-%d")
Date_val

r.dt<-setZ(r,Date_val)
names(r.dt)<-Date_val
 plot(r.dt)
indices <- format(as.Date(getZ(r.dt), format = "%Y-%b-%d"), format = "%Y")

Using this example, i can get the dates of maximum grid cell value with following function.

dtmx <- function (x,...) {
  if(all(is.na(x))) {result <- 0
  } else {result <- which.max(x)}
  return(result)
}

dtmxv <- stackApply(r.dt, indices, dtmx)
dtmxv

Here i do not want date of maximum value but the dates when the grid cell value is >0.75. How can i modify the function dtmx to achieve this ?

Lily Nature
  • 613
  • 7
  • 18
  • What should your `dtmx` function return exactly? The first value, where `x` is greater or equal to 0.75? All values, where `x` is greater or equal to 0.75? What should it return if x smaller to 0.75? Should it be `TRUE / FALSE`? ..please clarify, what you expect. – symbolrush Sep 26 '18 at 05:48
  • Thank you. right now the dtmx return the date when the grid cell value is maximum. I expect it to return all the dates that have greater than or equal to 0.75 grid cell value ( not only the maximum).If its is less than 0.75, its OK to get 0 or NA. – Lily Nature Sep 26 '18 at 05:55
  • replacing `else {result <- which.max(x)}` with `else {result <- which(x >= 0.75)}` should do the trick. This returns all indices where values are bigger or equal to 0.75 – symbolrush Sep 26 '18 at 06:06
  • I tried that but it through an error that that x must be numeric, integer or logical.Error in .local(x, values, ...) : values must be numeric, integer or logical. – Lily Nature Sep 26 '18 at 15:44

1 Answers1

0

It is not clear what exactly you are after in terms of output structure.

You can do

d <- r > .75
names(d) <- Dates$Date
plot(d)

If the data fits into memory you could do the below (if not you could do this in chunks, but the list could become very large).

a <- apply(as.matrix(d), 1, which)
head(a)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63