Create a gist now

Instantly share code, notes, and snippets.

@cvitolo /ts2years.R
Last active Aug 29, 2015

What would you like to do?
Split long time series into (hydrological) years in R
# 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