[R] extract index during execution of sapply

Ben Bolker bolker at ufl.edu
Fri Jun 22 15:23:08 CEST 2007

Christian Bieli <christian.bieli <at> unibas.ch> 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


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?

More information about the R-help mailing list