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@r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.