Skip to content
Prev 171697 / 398503 Next

Have a function like the "_n_" in R ? (Automatic count function )

On Wed, Feb 25, 2009 at 4:43 PM, Charles C. Berry <cberry at tajo.ucsd.edu> wrote:
Thank you - I think I finally understood how that code got parsed.
Does the text below describe things correctly?
First, Hadley defines a function that returns another function, like this:

function(){
 i <- 0
 function() {
   i <<- i + 1
   i
 }
}

Since the returned function is defined in a local environment , R
returns the function together with that local environment, and lexical
scoping can work it's magic
Finally Hadley evaluates the above defined function-returning
function, and stores the returned function in n.

n<-function(){
 i <- 0
 function() {
   i <<- i + 1
   i
 }
}()

*Phew*
That wasn't too difficult after all :-)

/Gustaf