Created
November 23, 2019 21:41
-
-
Save kokkytos/76a283a770df10c05b4fb4ce97e2b40e to your computer and use it in GitHub Desktop.
The purpose is to compare whether the indexes of names from the result of the stackApply function correspond to the indexes that were defined as parameter input. An alternative method (ver_median function) is used for comparison.
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 = 300, ncols = 300, res = 500, | |
xmn = 0, | |
xmx = 150000, | |
ymn = 0, | |
ymx = 150000) | |
n=3000 | |
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)) | |
# Print the results | |
stackapply_median | |
ver_median |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment