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

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Wed Feb 25 17:03:38 CET 2009

```hadley wickham wrote:
> On Wed, Feb 25, 2009 at 8:41 AM, Wacek Kusnierczyk
> <Waclaw.Marcin.Kusnierczyk at idi.ntnu.no> 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.
>

not as it stands above, because you immediately apply your function and
lose grip of it -- so it's just as do-once a solution as that with
local.  but clearly, to have multiple independent counters, you'd need
two nested functions, as in this generalized version:

make.counter =
function(value)
function(increment)
(value <<- value + increment)[1]

counters =
lapply(rep(0, 3), make.counter)
mapply(
function(counter, increment)
counter(increment),
counters, 1)
# 1 1 1

which is what you presumably had in mind, roughly.

vQ

```