rdata.table

Iterate over rows until a specific value is reached


I have a data.table

dt <- data.table(
   Date = c("20240701", "20240801", "20240901", "20241001"),
   Plan          = c(85,17,50, 34),
   OpenPlan      = c(85, 0,33, 0),
   ValuetoReduce = c(97,97,97,97)
  )

I want to reduce "Plan" over all periods in total by 97 (ValuetoReduce)

In my mind this looks like:

New dt should like look like

dt_new <- data.table(
  Date = c("20240701", "'20240801", "20240901", "20241001"),
  Plan          = c(85,17,50, 34),
  OpenPlan      = c(85, 0,33, 0),
  ValuetoReduce = c(97,97,97,97),
  NewPlan       = c(0,17,38,34)
 )

Thanks!


Solution

  • I too have not checked all cases, but does this do the job?

    f <- \(e,o,m) {
      k = pmin(m, cumsum(o))
      e-c(k[1],diff(k))
    }
    
    dt[, NewPlan:=f(Plan,OpenPlan,max(ValuetoReduce))][]
    

    Output:

           Date  Plan OpenPlan ValuetoReduce NewPlan
         <char> <num>    <num>         <num>   <num>
    1: 20240701    85       85            97       0
    2: 20240801    17        0            97      17
    3: 20240901    50       33            97      38
    4: 20241001    34        0            97      34