Optimized recursive sequence computation

What is the fastest way in R to compute a recursive sequence defined as

x[1] <- x1 
x[n] <- f(x[n-1])

I assume that the eigenvector x is pre-distributed. Is there a smarter way than just looping?

Option: extend it to vectors:

 x[,1] <- x1 
 x[,n] <- f(x[,n-1])
+3
source share
5 answers

, "", , , , "". , . " " . , , : .

, . , . . , . Etc. . . S-Plus.

+4

;)

+3

, , ? , O (1), , O (n), .

+1

x $y < - f (z) x , , x - . , , R , [[<- . , :

x[[1]] <- x1 
for (m in seq(2, n))
    x[[m]] <- f(x[[m-1]])

, n-1 for, , , , . while, . (lapply ..) ...

( , , , , .)

. Chambers (2008). . . 473-474.

+1
source

You can write it in C / C ++ / Fortran and use the convenient built-in package to solve compilation, linking and loading for you.

Of course, your function f()can be a real limitation if you want to remain a function of R. Rcpp has an example of a callback from-C ++ - to-R, but this requires a bit more work than just using inline.

+1
source

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


All Articles