Skip to content

Instantly share code, notes, and snippets.

@timriffe
Created May 19, 2022 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timriffe/8201ab77e4c9d64967949a4fc9af9b47 to your computer and use it in GitHub Desktop.
Save timriffe/8201ab77e4c9d64967949a4fc9af9b47 to your computer and use it in GitHub Desktop.
testing methods for monotonic interpolation
library(lubridate)
# options for a truly monotonic case:
set.seed(1)
values <- runif(100) %>% cumsum() %>% '*'(100) %>% round()
all_dates <- seq(dmy("01.01.2020"),today(), by = "days")
my_dates <- sample(all_dates, size = 100, replace = FALSE) %>% sort()
plot(my_dates, main = "irregularly spaced dates")
sum(day(my_dates) == 1) # just 4 days are 1st of month
# linear interpolation:
(first_of_month <- all_dates[day(all_dates) == 1])
# could filter down to only dates contained within the range of my_dates
# this assumes the first value is entirely contained in its month,
# possibly not true.
approx(my_dates, values, xout = first_of_month)$y %>% c(0,.) %>% diff()
# If that's bad then remove the 0 part in front.
# or a monotonic spline. This one doesn't seem to like using Date class for x,
# but it works same if you coerce to integer
splinefun(as.integer(my_dates), values, method = "monoH.FC")(as.integer(first_of_month))
# Question: if we use a monotonic spline, what happens if the data aren't monotonic?
values2 <- values
values2[9:10]
values2[10] <- 540
values2[30]
values2[31:34] <- 1480
splinefun(as.integer(my_dates), values2, method = "monoH.FC")(as.integer(first_of_month))
# It doesn't seem to want to spit back negatives. Are we satisifed with this?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment