Skip to content
Back to formatted view

Raw Message

Message-ID: <f8e6ff050902250701u5526ee03ucd866bc5dd7648ea@mail.gmail.com>
Date: 2009-02-25T15:01:40Z
From: Hadley Wickham
Subject: Have a function like the "_n_" in R ? (Automatic count function )
In-Reply-To: <49A5587D.7030905@idi.ntnu.no>

On Wed, Feb 25, 2009 at 8:41 AM, Wacek Kusnierczyk
<Waclaw.Marcin.Kusnierczyk at idi.ntnu.no> wrote:
> hadley wickham 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
>> ? }
>> })()
>>
>
> actually, you do not need the external function to have the functionality:
>
> ? ?n = local({
> ? ? ? ?i = 0
> ? ? ? ?function() (i <<- i + 1)[1] })
>
> ? ?n()
> ? ?# 1
> ? ?n()
> ? ?# 2

Yes, I'm just using the function as a way of creating an environment.
The function method is a little more flexible if you want multiple
independent counters though.

Hadley



-- 
http://had.co.nz/