How to obtain Dates of annual maximum gridcell val

2019-03-04 13:44发布

How can i get two rasters that gives the maximum value for each grid cells per year and also gives the dates on which that maximum value has occured. Below is the reproducible example with some steps i have implemented.

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)

# Get indices to make annual maxima value for each grid cells

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

# Implement stackApply to get maximum value each year.

rmax<-stackApply(r.dt,indices = indices,fun=max,na.rm=T)
plot(rmax)

1条回答
冷血范
2楼-- · 2019-03-04 14:31

You can do

wmax <- stackApply(r.dt, indices = indices, fun=function(i,...) which.max(i))

to get the indices that refer to the Date vector

To get (integer) date representations, i.e., the number of days since 1970-01-01, you could do something like this, for each year

m2000 = data.frame(from=1:3, to=as.integer(Date_val)[1:3])
x <- subs(wmax[[1]], m2000)
查看更多
登录 后发表回答