Vectorize a product calculation which depends on previous elements?

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

    I think this is cheating and not generalizable, but: according to the rules you have above, any occurrence of 1 in the vector will make all subsequent elements 1 (by recursion: z[i] is 1 set to 1 if z[i-1] equals 1; therefore z[i] will be set to 1 if z[i-2] equals 1; and so forth). Depending on what you really want to do, there may be such a recursive solution available if you think carefully about it ...

    z <- c(1,1,0,0,0,0)
    first1 <- min(which(z==1))
    z[seq_along(z)>first1] <- 1
    

    edit: this is wrong, but I'm leaving it up to admit my mistakes. Based on a little bit of playing (and less thinking), I think the actual solution to this recursion is more symmetric and even simpler:

    rep(z[1],length(z))
    

    Test cases:

    z <- c(1,1,0,0,0,0)
    z <- c(0,1,1,0,0,0)
    z <- c(0,0,1,0,0,0)
    
    0 讨论(0)
提交回复
热议问题