-3

I'd like to save the output of my recursive function as a list.

> (getNames(74, foo))
[1] "Excavata"
[1] "Excavata"
[1] "Excavata"
[1] "Excavata"
[1] "Stramenopiles"
[1] "Stramenopiles"
[1] "Stramenopiles"
[1] "Excavata"
[1] "Excavata"
[1] "Metazoa"

How do I go about doing this? Maybe this is simpler than I think but I've been stuck for a couple of days!

I don't think the code here matters: the general idea of my question regards saving the output of a recursive function (such as towers of hanoi) as a data type such as a list or a data.frame.

user1317221_G
  • 15,087
  • 3
  • 52
  • 78
laemtao
  • 147
  • 11
  • Exact code may not matter, but it's always easier to answer a question that provides a reproducible example. – Gregor Thomas Feb 14 '13 at 23:44
  • 1
    Please make your example [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)! This will be hard to answer without knowing what your `recursive` function does, and how it does it. – mnel Feb 14 '13 at 23:45
  • Not clear to me what you want. Can you give an example function and inputs and the desired output of this "convert to list" operation you're looking for? – scott Feb 14 '13 at 23:46

2 Answers2

4

If you really think the exact code doesn't matter:

recursive_add <- function(x, res_list=NULL) {
  if (is.null(res_list)) {
    res_list <- list()
  }
  if (x == 26) {
    return(res_list)
  }
  res_list[[x]] <- letters[x]
  res_list <- recursive_add(x + 1, res_list)
  return(res_list)
}
recursive_add(1)

The default NULL argument allows you to create a new list the first time, but then pass the existing list down to the recursive calls.

Marius
  • 58,213
  • 16
  • 107
  • 105
0

Without code to see I'm not sure as to whether it would be useful, but have you considered using rapply? rapply help page its a recursive version of lapply and lapply returns lists as output.

SJWard
  • 3,629
  • 5
  • 39
  • 54