I am trying to build a function that keeps values constant for a certain amount of months (rows) in a time series. I already have a function which keeps values constant as long as the following rows are NAs. I would like to change the function (or make a new one) in a way so that it keeps the following rows constant for a certain amount of months.
This is my function:
na_locf_until = function(x, n) {
# in time series data, fill in na's until indicated n
l <- cumsum(! is.na(x))
c(NA, x[! is.na(x)])[replace(l, ave(l, l, FUN=seq_along) > (n+1), 0) + 1]
}
Example:
htm <- data.frame (Date = c("Jan 2001", "Feb 2001", "Mar 2001", "Apr 2001", "May 2001", "Jun 2001", "Jul 2001", "Aug 2001", "Aug 2001"),
prc = c(34,35,38,24,22,18,30,32,38),
buy = c(1, 1, 1, 0, 0, 1, 0, 0, 0),
htm_prc = c(34,34,38,38,22,18,18,32,38))
The binary column indicates in Jan 2001 buy. The function should keep - in a next column (or the same) - the value 24 constant for e.g. this month and the next month if the binary variable was 1. I struggle, as i do not want the htm_prc value in Feb 2001 to be 35. Column htm_prc shows my desired outcome.
Maybe my function works as an inspiration.
Thanks in advance!!