Output from recursive function R

1.4k views Asked by At

I'm trying to write a simple recursive function in R which each time will return just a single number. I want to store these in a column basically. So initially I'm declaring something like relevant=c(rep(0,16)) then if it satisfies some criteria I want to change the corresponding values of relevant[j] to 1. if(something==1){ relevant[j]=1 }

But then when I call relevant outside the function all the values are 0. The criteria is definitely being satisfied, but it just doesn't seem to change the values!

Any help would be appreciated!

2

There are 2 answers

0
Cath On

Here is a "simple enough recursive function" that will return a vector of numbers, each one being calculated inside the function:

serf <- function(x){
            if (length(x)==5) {
              return(x)
            } else {
               x <- c(x, x[length(x)]+1) ; serf(x)
            }
        }


serf(1)
#[1] 1 2 3 4 5

Is that what you had in mind ?

0
John Fox On

It's not entirely clear to me what you want to do, but I interpret it as having a recursive function that returns a single value and wanting as well to accumulate the results of the recursive calls as a side effect.

Here's an example based on computation of Fibonacci numbers that solves this problem using a closure. A couple of caveats: (1) This is a terribly inefficient way to compute Fibonacci numbers. (2) Building up an object like values element-wise is very inefficient in R; if you know the length of the result in advance, it's much better to initialize the object to that length and then index into it.

> makefib <- function(){
+   values <- vector("numeric")
+   function(n){
+     if (n == 0) return(values)
+     res <- if (n < 3) 1 else Recall(n - 1) + Recall(n - 2)
+     values[length(values) + 1] <<- res
+     res
+   }
+ }   

> fib <- makefib()
> fib(6)
 [1] 8
> fib(0)
 [1] 1 1 2 1 3 1 1 2 5 1 1 2 1 3 8

I hope this helps.