Skip to content

Instantly share code, notes, and snippets.

@cvitolo
Last active August 29, 2015 14:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cvitolo/e2ec4887f376e3b7d912 to your computer and use it in GitHub Desktop.
Save cvitolo/e2ec4887f376e3b7d912 to your computer and use it in GitHub Desktop.
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