【发布时间】:2021-10-04 09:07:52
【问题描述】:
我最近遇到了一个有趣的问题,即使用其倒数第二个值作为.init 参数加上一个附加向量的当前值来计算向量值。这是样本数据集:
set.seed(13)
dt <- data.frame(id = rep(letters[1:2], each = 5), time = rep(1:5, 2), ret = rnorm(10)/100)
dt$ind <- if_else(dt$time == 1, 120, if_else(dt$time == 2, 125, as.numeric(NA)))
id time ret ind
1 a 1 0.005543269 120
2 a 2 -0.002802719 125
3 a 3 0.017751634 NA
4 a 4 0.001873201 NA
5 a 5 0.011425261 NA
6 b 1 0.004155261 120
7 b 2 0.012295066 125
8 b 3 0.002366797 NA
9 b 4 -0.003653828 NA
10 b 5 0.011051443 NA
我要计算的是:
ind_{t} = ind_{t-2}*(1+ret_{t})
我尝试了以下代码。由于.init 在这里没有用,我尝试取消原来的.init 并创建了一个虚拟.init,但不幸的是它不会将新创建的值(从第三行向下)拖到计算中:
dt %>%
group_by(id) %>%
mutate(ind = c(120, accumulate(3:n(), .init = 125,
~ .x * 1/.x * ind[.y - 2] * (1 + ret[.y]))))
# A tibble: 10 x 4
# Groups: id [2]
id time ret ind
<chr> <int> <dbl> <dbl>
1 a 1 0.00554 120
2 a 2 -0.00280 125
3 a 3 0.0178 122.
4 a 4 0.00187 125.
5 a 5 0.0114 NA
6 b 1 0.00416 120
7 b 2 0.0123 125
8 b 3 0.00237 120.
9 b 4 -0.00365 125.
10 b 5 0.0111 NA
我想知道是否可以对此代码进行一些调整并使其完全正常工作。 非常感谢您提前提供的帮助
【问题讨论】:
标签: r purrr rolling-computation accumulate