Vectorize a product calculation which depends on previous elements?

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

    Sometimes you just need to think about it totally differently. What you're doing is creating a vector where every item is the same as the first if it's a 1 or 0 otherwise.

    z <- c(1,1,0,0,0,0)
    if (z[1] != 1) z[1] <- 0
    z[2:length(z)] <- z[1]
    

提交回复
热议问题