Last active
August 29, 2015 14:10
-
-
Save cvitolo/e2ec4887f376e3b7d912 to your computer and use it in GitHub Desktop.
Split long time series into (hydrological) years in R
This file contains hidden or 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
# Load library | |
library(xts) | |
# Generate dummy time series | |
from <- as.Date("1950-01-01") | |
to <- as.Date("1990-12-31") | |
myDates <- seq.Date(from=from,to=to,by="day") | |
myTS <- as.xts(runif(length(myDates)),order.by=myDates) | |
# SPLIT THE TIME SERIES INTO CALENDAR YEARS | |
myList <- tapply(myTS, format(myDates, "%Y"), c) | |
plot(myList[[1]]) | |
# SPLIT THE TIME SERIES INTO HYDROLOGICAL YEARS | |
# calculate the number of hydrological years | |
nHY <- length(split(myTS[.indexmon(myTS) %in% 0:8], f="years"))-1 | |
# create an empty table , to be populate by a loop | |
myList <- list() | |
for ( counter in 1:nHY ){ | |
oct2dec <- split(myTS[.indexmon(myTS) %in% 9:11], f="years")[[counter]] | |
jan2sep <- split(myTS[.indexmon(myTS) %in% 0:8], f="years")[[counter + 1]] | |
myList[[counter]] <- rbind(oct2dec, jan2sep) | |
} | |
# Access the element of the list using the index, e.g. for plotting: | |
plot(myList[[1]]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment