0

excess <- excess %>% rename(Supply = Count.x, Demand = Count.y) %>% mutate(Excess = ifelse(!is.na(lag(Excess_per_month)), Excess_per_month + lag(Excess), Excess_per_month))

I tried to calculate Excess from the previous cell, lag doesnt work. This is in an R shiny framework, where I add excel file to calculate some stuff. lag(Excess_per_month) doesn't work since it only lags for the previous month, not the months before. Basically what is needed is Excess = Excess_per_month + lag(Excess)

r2evans
  • 141,215
  • 6
  • 77
  • 149
yashas107
  • 1
  • 1
  • 1
    Welcome to Stack Overflow. Please see the guidance on [how to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). It sounds like you may be looking for something like [`cumsum()`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/cumsum.html) but you are much more likely to get quick, helpful answers to your question if you post some a small example of input data and expected output. – SamR Aug 29 '23 at 08:25

1 Answers1

1

It sounds like you want a cumulative addition between NA values.

I'll fake some data and demonstrate the use of Reduce(..., accumulate=TRUE) and purrr::accumulate (if you're already using purrr).

vec <- 1:20
vec[c(5,11,17)] <- NA
vec
#  [1]  1  2  3  4 NA  6  7  8  9 10 NA 12 13 14 15 16 NA 18 19 20

Reduce(function(prev, this) ifelse(is.na(prev), this, prev + this), vec, accumulate = TRUE)
#  [1]  1  3  6 10 NA  6 13 21 30 40 NA 12 25 39 54 70 NA 18 37 57

purrr::accumulate(vec, ~ ifelse(is.na(.x), .y, .x + .y))
#  [1]  1  3  6 10 NA  6 13 21 30 40 NA 12 25 39 54 70 NA 18 37 57
r2evans
  • 141,215
  • 6
  • 77
  • 149