[R] How to iterate through two objects of class "list" fast?

Wolski wolski at molgen.mpg.de
Wed Jun 2 17:20:35 CEST 2004


Hallo!

Hi I was checking the performance of the for loop and mapply with system.time()

Case a)
the result list is allocated. It is the same list which element i pass as an argument.
e.g.
list2[[x]] <- myfunc(list2[[x]],list3[[x]])
24.18 s

Case b)
the same with mapply(myfunc,list2,list3)
1.96 s

Case c)
I have adjuested my function with a helper function to work with apply
tmp<-function(xx,oby)
{
myfunc(xx,oby[[xx at info]])
}
and than apply(obx,tmp,oby)
0.36 s

And finally 

Case d)
res<-list(length(oby))
res[[x]] <- myfunc(list2[[x]],list3[[x]])
0.36 s

I am Impressed

Thanks a lot Thomas L and Peter D.
Sincerely
Eryk



*********** REPLY SEPARATOR  ***********

On 6/2/2004 at 7:39 AM Thomas Lumley wrote:

>>>On Wed, 2 Jun 2004, Peter Dalgaard wrote:
>>>
>>>> "Wolski" <wolski at molgen.mpg.de> writes:
>>>>
>>>> > list3[[x]] <- myfunc(list1[[x]],list2[[x]])
>>>> >
>>>> > Until now I am runnign this in a for(x in 1:length(list1)) loop. But
>>>"for" loops are slow especially if list3 is HUGE.
>>>> >
>>>> > What can I do?
>>>>
>>>> Use mapply(). I wouldn't expect the for loop to be all that slow
>>>> unless you have forgotten to allocate memory for the result list up
>>>> front, though.
>>>>
>>>
>>>If you preallocate the memory the for loop is probably faster than
>>>mapply().
>>>
>>>	-thomas



Dipl. bio-chem. Eryk Witold Wolski    @    MPI-Moleculare Genetic   
Ihnestrasse 63-73 14195 Berlin       'v'    
tel: 0049-30-83875219               /   \    
mail: wolski at molgen.mpg.de        ---W-W----    http://www.molgen.mpg.de/~wolski




More information about the R-help mailing list