Avoid loopbacks in a recursive formula

I have the following data:

> set.seed(0)
> x <- c(1,rep(0, 15)) ; x
 [1] 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
> y <- rnorm(length(x)) ; y
 [1]  1.262954285 -0.326233361  1.329799263  1.272429321  0.414641434 -1.539950042 -0.928567035
 [8] -0.294720447 -0.005767173  2.404653389  0.763593461 -0.799009249 -1.147657009 -0.289461574
[15] -0.299215118 -0.411510833

      

I would like to fill in x

, using the following rule: x(t) = x(t-1)*y(t)

.

I can use a for loop

for (t in 2:length(x))
  x[t] <- x[t-1]*y[t]
x

      

To obtain:

[1]  1.000000e+00 -3.262334e-01 -4.338249e-01 -5.520115e-01 -2.288868e-01  3.524743e-01 -3.272960e-01
 [8]  9.646083e-02 -5.563063e-04 -1.337724e-03 -1.021477e-03  8.161696e-04 -9.366828e-04  2.711337e-04
[15] -8.112730e-05  3.338476e-05

      

Is there an efficient way to accomplish the above without using loops and therefore apply it to large datasets?

+3


source to share





All Articles