[R] recursion and lexical scoping

Thomas Lumley thomas at biostat.washington.edu
Tue Mar 21 18:47:25 CET 2000


On Tue, 21 Mar 2000, Denis White wrote:

> To assign values to a matrix in a recursive function,
> must the matrix be passed as argument and returned
> as value?

It doesn't _have_ to be. It depends on a compromise between slowness and
incomprehensibility.

You can use <<- to assign to a 'global' variable: eg
R> a<-matrix(0,ncol=5,nrow=10)
R> f
function(n) {
if (n==1) {
a<<-a+1
return(1)
}
else return(f(n-1)+f(n-1))
}

but it can get messy writing recursive functions with side-effects.

If you declare the matrix to be the correct size and only assign to
elements of it then I don't think it will be unnecessarily duplicated, so
the loss of efficiency won't be too bad.

	-thomas

Thomas Lumley
Assistant Professor, Biostatistics
University of Washington, Seattle

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list