rfunctioncatalan

Recursive method for Catalan numbers in R


I am trying to write a function in R that would take an input numb and output the corresponding Catalan number. For your information, the recursive formula for Catalan Numbers is,

C_0 = 1; 
C_n = {(4n - 2)*C_(n-1)}/(n+1)

My code is as follows,

catalan_num_recr <- function(numb){
  if (numb == 0){
    return(1)
  }
  else
    return(((4*numb-2)*catalan_num_recr(numb-1))/(numb+1))
}

When I run the function, I get,

> catalan_num_recr(3)
[1] 5

Which is correct.

AIM: However, I am trying to find Catalan's numbers for a range, I would like to find something like, catalan_num_recr(1:10).

PROBLEM: This does not work with my function, I get the following warning,

Warning messages:
1: In if (numb == 0) { :
  the condition has length > 1 and only the first element will be used

And a lot of wrong values as output,

> catalan_num_recr(1:15)
 [1] 1.000000 2.000000 2.500000 2.800000 3.000000 3.142857 3.250000
 [8] 3.333333 3.400000 3.454545 3.500000 3.538462 3.571429 3.600000
[15] 3.625000

Can someone help me modify my function/or help me see through the problem?

Regards.


Solution

  • Use Vectorize which takes a function and returns a new function which is essentially a wrapper to your function that accepts vectorised input. The computation is actually performed repeatedly by mapply so it won't be as fast as writing a function that is vectorised by hand.

    Vectorize(catalan_num_recr)(1:15)
     [1]       1       2       5      14      42     132     429    1430    4862
    [10]   16796   58786  208012  742900 2674440 9694845