Skip to content

Instantly share code, notes, and snippets.

@AdeelK93
Created June 2, 2017 05:57
Show Gist options
  • Save AdeelK93/7e6e3e2a14dcb64b0c633b55593ac948 to your computer and use it in GitHub Desktop.
Save AdeelK93/7e6e3e2a14dcb64b0c633b55593ac948 to your computer and use it in GitHub Desktop.
Jagged to monotonic time series
as.monotonic <- function(x) {
while(sum(diff(x)<0)) {
lastMonotonic <- which(diff(x)<0)
firstNonMonotonic <- lastMonotonic[1] + 1
# which chunk of the time series needs to be adjusted up
lastNonMonotonic <- ifelse(length(lastMonotonic)>1, lastMonotonic[2], length(x))
monotonicRange <- firstNonMonotonic:lastNonMonotonic
# add last monotonic value to nonmonotonic chunk
x[monotonicRange] <- x[monotonicRange] + x[lastMonotonic[1]]
}
x
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment