0

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!!

  • 2
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jan 09 '23 at 18:36
  • thanks. I included an example – Freddy Müller Jan 09 '23 at 18:40
  • the expected output is column htm_prc and it is based on the column prc. – Freddy Müller Jan 09 '23 at 18:42

1 Answers1

0

Perhaps this helps

library(dplyr)
library(data.table)
htm %>% 
  mutate(grp = rleid(buy|lag(buy))) %>% 
  group_by(grp) %>% 
  mutate(grp2 =as.integer(gl(n(), 2, n()))) %>% 
  group_by(grp2, .add = TRUE) %>%
  mutate(htm_prc2 = if(1 %in% buy) first(prc) else prc) %>%
  ungroup %>%
  select(-grp, -grp2)

-output

# A tibble: 9 × 5
  Date       prc   buy htm_prc htm_prc2
  <chr>    <dbl> <dbl>   <dbl>    <dbl>
1 Jan 2001    34     1      34       34
2 Feb 2001    35     1      34       34
3 Mar 2001    38     1      38       38
4 Apr 2001    24     0      38       38
5 May 2001    22     0      22       22
6 Jun 2001    18     1      18       18
7 Jul 2001    30     0      18       18
8 Aug 2001    32     0      32       32
9 Aug 2001    38     0      38       38
akrun
  • 874,273
  • 37
  • 540
  • 662