我有一个正数向量,使得
- 如果数字大于或等于 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 循环的情况下做到这一点?

最佳答案

以下是一些仅使用基础 R 的替代方案:

1) 减少

sumprod <- function(x, y) if (y < 1) x * y else x + y
Reduce(sumprod, x, acc = TRUE)
## [1]  3.000  2.700  2.430  3.430  6.430  5.787  8.787 11.787 12.787 13.787

2) 递归
cumsumprod_ <- function(x, init) {
      if (length(x)) c(init, Recall(x[-1], sumprod(tail(init, 1), x[1])))
      else init
}
cumsumprod <- function(x) {
      if (length(x) < 2) x
      else cumsumprod_(x[-1], x[1])
}

cumsumprod(x)
## [1]  3.000  2.700  2.430  3.430  6.430  5.787  8.787 11.787 12.787 13.787

更新: 修复了 (2) 中的边缘情况。

10-08 09:06