首先是样本数据
set.seed(123)
dat <- tibble(x = sample(-10:10, size = 11,replace = T))
# A tibble: 11 x 1
x
<int>
1 -4
2 6
3 -2
4 8
5 9
6 -10
7 1
8 8
9 1
10 -1
11 10
我有一个变量y,初始值为2.我想通过使用以下步骤在给定时间步骤中将x
添加到y来计算y的最终值:
y[i] = y[i-1] + x[i]
dat %>% mutate(y = accumulate(x, ~ .x + .y, .init = 2)[-1])
# A tibble: 11 x 2
x y
<int> <dbl>
1 -4 -2
2 6 4
3 -2 2
4 8 10
5 9 19
6 -10 9
7 1 10
8 8 18
9 1 19
10 -1 18
11 10 28
然而,我想强加的条件是,在给定的时间步长中,y不能是&gt; 10或否定。如果y> 10,10,如果y <10。 0,0。因此,实际
y(如下面的y1所示)应为:
# A tibble: 11 x 2
x y y1
<int> <dbl>
1 -4 -2 0 (-2 converted to 0)
2 6 4 6
3 -2 2 4
4 8 10 10 (12 converted to 10)
5 9 19 10 (19 converted to 10)
6 -10 9 0
7 1 10 1
8 8 18 9
9 1 19 10
10 -1 18 9
11 10 28 10 (19 converte to 10)
答案 0 :(得分:4)
您只需要重新定义用于accumulate
的功能:
library(tidyverse)
set.seed(123)
dat <- tibble(x = sample(-10:10, size = 11,replace = T))
fn <- function(x, y) pmax(pmin(x + y, 10), 0)
dat %>%
mutate(y = accumulate(x, fn, .init = 2)[-1])
dat
# A tibble: 11 × 2
x y
<int> <dbl>
1 -4 0
2 6 6
3 -2 4
4 8 10
5 9 10
6 -10 0
7 1 1
8 8 9
9 1 10
10 -1 9
11 10 10
工作原理:pmax
取两个值中的最大值,pmin
取最小值,因此将x+y
的总和换算为上限和下限以限制结果限制你需要。
答案 1 :(得分:2)
dat %>% mutate(y = accumulate(x, ~min(max(.x + .y, 0), 10), .init = 2)[-1])