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

Matteo Richiardi matteo.richiardi at gmail.com
Sat May 28 02:31:41 CEST 2016


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



More information about the R-help mailing list