Vectorize a product calculation which depends on previous elements?

前端 未结 7 1999
小鲜肉
小鲜肉 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:16

    Check out the rollapply function in zoo.

    I'm not super familiar with it, but I think this does what you want:

    > c( 1, rollapply(z,2,function(x) x[1]) )
    [1] 1 1 1 1 1 1
    

    I'm sort of kludging it by using a window of 2 and then only using the first element of that window.

    For more complicated examples you could perform some calculation on x[1] and return that instead.

提交回复
热议问题