Re: [R] r: LOOPING

From: Duncan Murdoch <murdoch_at_stats.uwo.ca>
Date: Fri 08 Jul 2005 - 21:44:26 EST

Vehbi Sinan Tunalioglu wrote:
> Uwe Ligges wrote:
>

>>Clark Allan wrote:
>>
>>>i know that one should try and limit the amount of looping in R
>>>programs. i have supplied some code below. i am interested in seeing how
>>>the code cold be rewritten if we dont use the loops.
>>
>>It is not always a good thing to remove loops (without having looked at 
>>each details of the code below).
>>"Compromise" is the keyword.

>
>
> If you have big routines for each iteration and especially you have back
> references in the data structures you are manipulating, it becomes
> really _hard to translate_ loop statements to filter-map-accumulator
> routines provided by R (i.e. *apply functions). I really cannot find my
> way in some situations. What I did so far is to write those routines in
> C. Dirty hack :(

It shouldn't be so hard to do this in R. Functions have access to the variables that are visible in the environment where they were created. So something like

x <- rnorm(10)
for (i in 2:10) {

    print(x[i]-x[i-1])
}

can be translated pretty literally as

x <- rnorm(10)
sapply(2:10, function(i) print(x[i]-x[i-1]))

This is not true in S-PLUS, so if you want portability, you'll need to do it in a different way.

> Maybe one should write a tutorial: "Howto avoid loops in R" by giving
> possible scenarios.

I don't think it's necessary. Loops really aren't so bad.

Duncan Murdoch



R-help@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 Received on Fri Jul 08 21:48:58 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:33:24 EST