我有一个正数向量,使得
- 如果数字大于或等于 1,则相加
- 如果数字小于 1,则乘以累积和。
例如
> set.seed(0)
> x <- sample(c(0.9, 0.9, 0.9, 1:3), 10, replace=T)
> x
[1] 3.0 0.9 0.9 1.0 3.0 0.9 3.0 3.0 1.0 1.0
结果向量
3 2.7 2.43 3.43 6.43 5.787 8.787 11.787 12.787 13.787
有没有办法在不使用 for 循环的情况下做到这一点?
最佳答案
这是一个 tidyverse
使用 purrr::accumulate
替代@G.Grothendieck 的答案:
library(tidyverse)
accumulate(x, function(x, y) if_else(y < 1, x * y, x + y))
#> [1] 3.000 2.700 2.430 3.430 6.430 5.787 8.787 11.787 12.787 13.787
关于R cumsum 与基于值的乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46459367/