Skip to content

Recursive looping of a list in R

3 messages · Evans, Jim Lemon, Gerrit Eichner

#
I am trying to creat a list from a loop such that once you loop the value
obtained is appended onto the list, then you loop through that value to give
the next elemet of the list and the system continues recusively. To be clear
I am creating a list to contain elements of the following tree
probabilities;
<http://r.789695.n4.nabble.com/file/n4710898/help.png> . The elements of the
diagram should be presented in a list such that each level of the tree
represents elements in the list (only the coefficients are of interest). I
have this code to start with

j <- 0

while(j >= 0){
  
  j <- j+1
  
  occlist <- list(1)
  
  for(i in occlist[[j]]){
    
    occ_cell <- seq(i, i+1, by = 1)
    
    occllist <- list(occ_cell)
    
    occunlist <- as.vector(unlist(occllist, recursive = TRUE))
    
    occlist[[j]] <- occunlist
    
    print(occlist)
    
  }
}

Any assistance will be highly appreciated. Thanks.



--
View this message in context: http://r.789695.n4.nabble.com/Recursive-looping-of-a-list-in-R-tp4710898.html
Sent from the R help mailing list archive at Nabble.com.
#
Hi Evans,
I'm not sure whether this is what you want, but look at the code in
the listBuilder and listCrawler functions in the crank package.

Jim
On Sun, Aug 9, 2015 at 4:14 AM, Evans <evansochiaga at aims.ac.za> wrote:
#
Hi Evans,

not many people (incl. me) are going to guess the building law for your 
recursive structure from the -- in fact at first sight not so clear -- 
picture, but I have some comments inline below.

  Hth  --  Gerrit
If you use a while-loop without a termination criterion and, e.g., a call 
to break, in its body it would run forever (if the code in its body were 
correct). Start coding with a (finite) for-loop. (Or even better start 
setting j and i "by hand" and let your code be evaluated step by step.)
Here you create in each loop the same starting list (which I guess is not 
what you want/should):
So, as a consequence an error occurs for j >= 2 in the following for-loop, 
because occlist has always only 1 component:
The following two lines of code compensate each other, so seem to be 
superfluous: