[R] Recursion is slow

Bryan Keller bskeller at wisc.edu
Thu Sep 3 23:10:38 CEST 2009


The following recursion is about 120 times faster in C#.  I know R is not known for its speed with recursions but I'm wondering if anyone has a tip about how to speed things up in R.

#"T" is a vector and "m" is a number between 1 and sum(T)

A <- function(T,m) {
lt <- length(T)

if (lt == 1) {
	if (0 <= m & m <= T[1]) {
		return(1)
		} else {
		return(0)
	}
}
R <- 0
for (u in 0:T[lt]) {
	R <- (R+(A(T[1:(lt-1)],(m-u))))
	}
return(R)
}

-------------
Bryan Keller, Doctoral Student/Project Assistant
Educational Psychology - Quantitative Methods
The University of Wisconsin - Madison




More information about the R-help mailing list