[R] Dynamically populate a vector by iteratively applying a function to its previous element.

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Sat May 28 03:14:22 CEST 2016

```You have set yourself an impossible goal. Either you can reformulate your problem as non-iterative and can process your data as arrays, or you have to use some kind of for loop. The lapply and Vectorize functions are popular "pretty" ways to do this, but they amount to hidden for loops.

Note that certain instances of iterative algorithms may have optimized compiled calculation functions ready for your use,  but unless someone has figured out some algorithm-specific optimization they won't be significantly faster than an R for loop.

The best you can do is avoid allocating growing data structures... pre-allocate your result and fill it in as you go.
--
Sent from my phone. Please excuse my brevity.

On May 27, 2016 5:31:41 PM PDT, Matteo Richiardi <matteo.richiardi at gmail.com> wrote:
>I want to dynamically populate a vector by iteratively applying a
>function to its previous element, without using a 'for' cycle. My
>solution, based on a question I posted some times ago for a more
>complicated problem (see "updating elements of a list of matrixes
>without 'for' cycles") was to define a matrix of indexes, and then
>apply the function to the indexes. Here's a trivial example:
>
># my vector, all elements still unassigned
>v <- rep(NA, 10)
># initialisation
>v[1] <- 0
>
># the function to be applied
>v.fun = function(x) {
>  i <- x[1]
>  return(v[i]+1)
>}
>
># The matrix of array indices
>idx <- as.matrix(expand.grid(c(1:9)))
>
># Application of the function
>r[2:10] <- invisible(apply(idx, 1, v.fun))
>
>[Note that this example is deliberately trivial: v <-c(0:9) would
>solve the problem. In general, the function can be more complicated.]
>
>The trick works only for v[2]. I imagine this is because the vector is
>not dynamically updated during the iteration, so all values v[2:10]
>are retained as NA.
>
>How can I solve the problem, without using a 'for' cycle?
>Thanks for your help ! Matteo
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help