I have data:
dat <- tibble(
day = 200:210,
x = sample(-10:10, size = 11,replace = T))
I have a variable y
df %>% mutate(y = 5 + cumsum(x))
or, with your extra conditions
df %>% mutate(y = (5 + cumsum(x)) %>% pmin(10) %>% pmax(0))
We could use accumulate
from purrr
. With accumulate
, do the recursive sum
of 'x' elements while initiating with a value of 5 (.init = 5
) and remove the first element of accumulate
output ([-1]
)
library(purrr)
library(dplyr)
dat %>%
mutate(y = accumulate(x, ~ .x + .y, .init = 5)[-1])
# A tibble: 11 x 3
# day x y
# <int> <int> <dbl>
# 1 200 4 9.00
# 2 201 3 12.0
# 3 202 -4 8.00
# 4 203 -7 1.00
# 5 204 -3 - 2.00
# 6 205 1 - 1.00
# 7 206 -5 - 6.00
# 8 207 -1 - 7.00
# 9 208 -4 -11.0
#10 209 -2 -13.0
#11 210 4 - 9.00
A similar approach in base R
would be
dat$y <- Reduce(function(u, v) u + v , dat$x, init = 5, accumulate = TRUE)[-1]
dat$y
#[1] 9 12 8 1 -2 -1 -6 -7 -11 -13 -9