[R] Recursion in R ...

Uwe Ligges ligges at statistik.uni-dortmund.de
Sat Jul 7 12:34:03 CEST 2007



Alberto Monteiro wrote:
> Ted Harding wrote:
>> So I slickly wrote a recursive definition:
>>
>> Nnk<-function(n,k){
>>   if(n==1) {return(k)} else {
>>     R<-0;
>>     for(r in (1:k)) R<-(R+Nnk(n-1,k-r+1)) # ,depth))
>>   }
>>   return(R)
>> }
>>
> You are aware that this is equivalent to:
> 
> Nnk1 <- function(n, k) { prod(1:(n+k-1)) / prod(1:n) / prod(1:(k-1)) }

or

Nnk2 <- function(n, k) { gamma(n+k) / gamma(n+1) / gamma(k) }

or most easily:

Nnk3 <- function(n, k) choose(n+k-1, n)


Uwe Ligges




> aren't you?
>  
>> ON THAT BASIS: I hereby claim the all-time record for inefficient
>> programming in R.
>>
>> Challengers are invited to strut their stuff ...
>>
> No, I don't think I can bet you unintentionally, even though
> my second computer program that I ever wrote in life had to be
> aborted, because it consumed all the resources of the computer.
> 
> Alberto Monteiro
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list