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
performance for-loop r recursion


source to share


No one has answered this question yet

Check out similar questions:

2893
Looping through an array in JavaScript
2847
Improve SQLite performance per second per second?
2116
Why are stigmental additions much faster in individual cycles than in combined cycles?
1516
What is tail recursion?
1250
Replacing 32-bit loop counter with 64-bit values ​​leads to crazy performance deviations
881
When should I use a cross to apply over an inner joint?
845
'For' loop for iterating over an enum in Java
629
data.table vs dplyr: can something do good and other do bad or bad?
466
Read very large tables quickly as data
241
A pythonic way to combine a FOR and an IF loop



All Articles
Loading...
X
Show
Funny
Dev
Pics