简体   繁体   English

R cumsum基于值的乘法

[英]R cumsum with multiplication based on value

I have a vector of positive numbers such that - if the number is greater or equal to 1, it gets added - if the number is less than 1, it multiplies the cumulative sum. 我有一个正数向量,如果数字大于或等于1,它会被添加 - 如果数字小于1,它会累加累计和。

For example 例如

> 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

The resulting vector 得到的矢量

3  2.7  2.43  3.43  6.43  5.787  8.787  11.787  12.787  13.787

Is there a way to do it without using a for loop? 有没有办法在不使用for循环的情况下完成它?

And here's a tidyverse alternative to @G.Grothendieck's answer using purrr::accumulate : 而这里的一个tidyverse使用G.Grothendieck的回答@替代purrr::accumulate

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

Here are some alternatives using only base R: 以下是仅使用基数R的一些替代方案:

1) Reduce 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) Recursion 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

Update: Fixed edge case in (2). 更新: (2)中的固定边缘情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM