Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to vectorise the sequential update of the elements of a vector in R?

Is it possible to vectorise code like the following?

length(x) <- 100;
x[1]      <- 1;
y         <- rnorm(100);

for(i in 2:100) {
    x[i] <- 2 * y[i] * x[i-1];
}

I appreciate that this is a trivial example, but it serves to illustrate the idea.

I often need to write code where the i-th value in a vector depends on the (i-1)-th value and if possible, I'd like to write this without needing a for loop, as profiling suggests the functions with this type of operation are the major bottlenecks in my code.

Is this operation vectorizable so I do not need to use a for() loop in the calculation?

like image 253
kaybenleroll Avatar asked Jan 14 '11 19:01

kaybenleroll


2 Answers

In general, if you want a vectorised solution you need to solve the recurrence relation.

like image 90
hadley Avatar answered Sep 28 '22 04:09

hadley


In the example you have you could work out the formula for x[i] and see if it can be vectorized. In this case I think cumprod might work.

x <- c(1, cumprod(2*y)[1:99])

For some cases case you can also use the filter command in convolution or recursive mode. See ?filter

However if it is isn't possible to work out a formula for the n'th value that fits one of the molds above, you could try using a package like inline or Rcpp to write this in loop in C/C++.

like image 45
Sameer Avatar answered Sep 28 '22 04:09

Sameer