Re: [R] extract index during execution of sapply

From: Thomas Lumley <>
Date: Fri, 22 Jun 2007 07:45:14 -0700 (PDT)

On Fri, 22 Jun 2007, Ben Bolker wrote:

> Christian Bieli <christian.bieli <at>> writes:
>> Hi there
>> During execution of sapply I want to extract the number of times the
>> function given to supply has been executed. I came up with:
>> mylist <- list(a=3,b=6,c=9)
>> sapply(mylist,function(x)as.numeric(gsub("[^0-9]","",deparse(substitute(x)))))
>> This works fine, but looks quite ugly. I'm sure that there's a more
>> elegant way to do this.
>> Any suggestion?
>> Christian
> I would love to have an answer to this -- when I run
> into this kind of problem I usually end up using mapply:
> e.g., suppose I have
> mylist <- replicate(5,list(x=runif(10),y=runif(10)),simplify=FALSE)
> and I want to plot each element in a different color. I'd like
> to be able to do
> plot(0:1,0:1,type="n")
> lapply(mylist,plot,col=i)
> but instead I do
> mapply(function(x,i) points(x,col=i),mylist,1:5)
> would it be too ugly to have a special variable called INDEX
> that could be used within an sapply/lapply statement?

There are two distinct suggestions here: a variable that says *how many* times the function has been called, and a variable that say *which element* is currently being operated on. The first seems undesirable as order of evaluation really should not matter in the apply functions.

The second makes more sense but is still a little tricky. AFAICS there is no way for lapply() to find out whether FUN will accept an argument INDEX without an "unused argument(s)" error, so it can't just be passed as an argument. This suggests having yet another apply function, that would assume an INDEX argument and might be written

   yapply<-function(X,FUN, ...) {


However, I think it would be preferable in many cases for INDEX to be names(X) if it exists, rather than 1:n. In any case, it is easy to write the function.

         -thomas mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Fri 22 Jun 2007 - 14:54:41 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 22 Jun 2007 - 15:02:20 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.