[R] r: LOOPING

Duncan Murdoch murdoch at stats.uwo.ca
Fri Jul 8 13:44:26 CEST 2005


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




More information about the R-help mailing list