[R] Have a function like the "_n_" in R ? (Automatic count function )
Gustaf Rydevik
gustaf.rydevik at gmail.com
Wed Feb 25 17:13:01 CET 2009
On Wed, Feb 25, 2009 at 4:43 PM, Charles C. Berry <cberry at tajo.ucsd.edu> wrote:
> On Wed, 25 Feb 2009, Gustaf Rydevik wrote:
>
>> 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?
>
>
> i is not _defined_ as zero. It is initially _assigned_ the value of zero and
> is subsequently assigned other values.
>
> As for the details of what goes here, see
>
> An Introduction to R
> Section 10.7 Scope
>
> and study the open.acount() example there.
>
> HTH,
>
> Chuck
>
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
--
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