[R] Have a function like the "_n_" in R ? (Automatic count function )
Charles C. Berry
cberry at tajo.ucsd.edu
Wed Feb 25 16:43:25 CET 2009
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
>
> /Gustaf
>
> --
> Gustaf Rydevik, M.Sci.
> tel: +46(0)703 051 451
> address:Essingetorget 40,112 66 Stockholm, SE
> skype:gustaf_rydevik
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
Charles C. Berry (858) 534-2098
Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901
More information about the R-help
mailing list