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

Gustaf Rydevik gustaf.rydevik at gmail.com
Wed Feb 25 16:04:35 CET 2009


On Wed, Feb 25, 2009 at 3:30 PM, hadley wickham <h.wickham at gmail.com> wrote:
> And for completeness here's a function that returns the next integer
> on each call.
>
> n <- (function(){
>  i <- 0
>  function() {
>    i <<- i + 1
>    i
>  }
> })()
>
>> n()
> [1] 1
>> n()
> [1] 2
>> n()
> [1] 3
>> n()
> [1] 4
>> n()
> [1] 5
>> n()
> [1] 6
>
>
> ;)
>
> Hadley
>


*headache*!
I can't wrap my head around this one - too strange code!
Could someone please give a hint on what's going on?
How does"i<<- i+1" modify i permanently, seeing as i is defined as 0
to start with?

/Gustaf

-- 
Gustaf Rydevik, M.Sci.
tel: +46(0)703 051 451
address:Essingetorget 40,112 66 Stockholm, SE
skype:gustaf_rydevik




More information about the R-help mailing list