Is it possible to vectorize sequential updating of vector elements in R?

Can I digitize the code as follows?

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

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

I often have to write code where the i-th value in a vector depends on the (i-1) -th value, and, if possible, I would like to write this without using a for loop, as profiling assumes that functions with this type of operation are the main bottlenecks in my code.

Is this operation vectorized, so I donโ€™t need to use the for() loop in the calculation?

+4
source share
5 answers

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

+10
source

In the example, you can find 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]) 

In some cases, you can also use the filter command in convolution or recursion mode. See ?filter

However, if you cannot work out a formula for the nth value that matches one of the forms above, you can try using a package, such as inline or Rcpp , to write this in a loop in C / C ++.

+5
source

The interior of this graph command is equivalent. Itโ€™s quite interesting to run it many times:

plot (c (1, 2 ^ (2: length (x) -1) * cumprod (rnorm (99))))

+1
source

I donโ€™t have any detailed information about this yet, but it seems that the filter() function will be useful in order to do what I need.

0
source

In C ++ you can write non-authorized code:

 library(inline) myfun <- cxxfunction(signature(y="numeric"), body=' Rcpp::NumericVector yvec(y); int ysize = yvec.size(); Rcpp::NumericVector result(ysize); if (ysize > 0) { result[0] = 1; for (int i = 1; i < ysize; i++) { result[i] = 2 * yvec[i] * result[i-1]; } } return result; ', plugin="Rcpp") 

Then call this function from R:

 y <- rnorm(100); x <- myfun(y); 
0
source

Source: https://habr.com/ru/post/1335602/


All Articles