Evans Otieno
Evans Otieno

Reputation: 309

Recursive looping in r

I am new in R but I want to loop through elements of a given list recursively, to be presice I have alist of vectors where the first vector is given by (1,2,3,4), then I now want to loop through this vector and append the second vector obtained to the original list, again loop thorugh second vector in the list and get the third vector which is also appended on the original list and so on. I have this code to start with`

occlist <- list()
occ_cell <- c(1,2,3,4)

for(i in occ_cell){
  occ_cell <- seq(i,4*i, by = 1)
  occlist[[i]] <- occ_cell
}
`

gives the following list

#[[1]]
#[1] 1 2 3 4

#[[2]]
#[1] 2 3 4 5 6 7 8

#[[3]]
# [1]  3  4  5  6  7  8  9 10 11 12

#[[4]]
# [1]  4  5  6  7  8  9 10 11 12 13 14 15 16

I think to be more clear, lets have the following figure

In that image we have 2 levels and the values in each level should be appended to a list, again each level is computed from the previous level.(i.e. in level two we have values obtained from level one (1,2,3,4,) and values from level one is obtained from level 0 (1)

Upvotes: 2

Views: 2995

Answers (1)

Rorschach
Rorschach

Reputation: 32426

recOcc <- function(i) {
    if (i == 0) return ( NULL )
    append( recOcc(i-1), list(seq(i, 4*i)) )
}

And, call with (to reproduce your output)

recOcc(4)
# [[1]]
# [1] 1 2 3 4
# 
# [[2]]
# [1] 2 3 4 5 6 7 8
# 
# [[3]]
#  [1]  3  4  5  6  7  8  9 10 11 12
# 
# [[4]]
#  [1]  4  5  6  7  8  9 10 11 12 13 14 15 16

You can also use Recall to name your recursive function in the recursive call, which allows for the function name to change.

Edit

For the tree structure, you could try this

## i is the number to start the sequence
## depth determines how deep to recurse
recOcc2 <- function(i, depth=3, cur.depth=0) {
    if (depth==cur.depth) return(seq(i, 4*i))
    acc <- as.list(seq(i, 4*i))
    for (ii in seq_along(acc))
        acc[[ii]] <- recOcc2(acc[[ii]], depth, cur.depth+1)
    acc
}

## To recreate the simple list
res <- recOcc2(1, depth=1)

## For nested lists
res <- recOcc2(1, depth=2)

Upvotes: 3

Related Questions