Created
November 22, 2019 19:23
-
-
Save kokkytos/5d554b5a725bb48d2189e2d1fa0e2206 to your computer and use it in GitHub Desktop.
Calculate median per day of week
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Calculate median per day of week | |
library(lubridate) | |
library(raster) | |
library(magrittr) | |
r <- raster(nrows = 10, ncols = 10, res = 1, | |
xmn = 0, | |
xmx = 10, | |
ymn = 0, | |
ymx = 10) | |
n=2000 | |
mydates <- seq(as.Date("2012-01-19"), by = "day", length.out = n) | |
set.seed(5); | |
mystack <- raster::stack(lapply(1:n, function(i) {r<-raster::setValues(r,floor(runif(ncell(r), min=1, max=1000)));return(r)})) %>% | |
setNames(mydates) %>% | |
raster::setZ(mydates) | |
myindices <- lubridate::wday(raster::getZ(mystack), week_start = 1) # "Monday"=1, | |
### stackApply method | |
### | |
stackapply_median<- raster::stackApply(mystack, indices=myindices,fun=function(x,...){(median(x, na.rm = T))}) | |
#### my verification | |
#### | |
ver <- function(myday, s){ | |
sub_s <- raster::subset(s,which(lubridate::wday(raster::getZ(s),week_start = 1) == myday)) | |
m <- calc(sub_s, median,na.rm = T) | |
return(m) | |
} | |
ver_median <- raster::stack(sapply(c(1:7), ver, s=mystack)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment