Re: [R] extract index during execution of sapply

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

On Fri, 22 Jun 2007, Ben Bolker wrote:

> 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
>
> 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, ...) {

 	index<-seq(length.out=length(X))
         mapply(FUN,X,INDEX=index,MoreArgs=list(...))
        }

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



R-help_at_stat.math.ethz.ch 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. 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 https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.