Vectorize a product calculation which depends on previous elements?

前端 未结 7 1984
小鲜肉
小鲜肉 2020-12-04 22:23

I\'m trying to speed up/vectorize some calculations in a time series. Can I vectorize a calculation in a for loop which can depend on results from an earlier iteration? For

7条回答
  •  隐瞒了意图╮
    2020-12-04 23:17

    There is a function that does this particular calculation: cumprod (cumulative product)

    > cumprod(z[zi])
    [1] 1 0 0 0 0
    
    > cumprod(c(1,2,3,4,0,5))
    [1]  1  2  6 24  0  0
    

    Otherwise, vectorize with Rccp as other answers have shown.

提交回复
热议问题