[R] Operating on windows of data

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Mar 22 13:49:04 CET 2004


Ajay Shah <ajayshah at mayin.org> writes:

> This brings me to a question I've always had about "the R way" of
> avoiding loops. Yes, the sapply() approach above works. My question
> is: Why is this much better than writing it using loops?

It's often not so much a matter of avoiding the loops as such. Splus
had a memory-management issue that caused for loops to be extremely
slow, but with R it is often a toss-up. The real power of sapply() and
friends is that they offer a convenient and compact way of looping
*and* collecting results.

Compare

vectorize <- function(FUN)function(x)sapply(x,FUN)

to 

vectorize <- function(FUN) function(x){
        res <- numeric(length(x))
        for (i in seq(along=x))
           res[i] <- FUN(x[i])
        res
    }

and notice that they don't actually do the same thing since sapply is
better at adjusting to the return value of FUN. On the other hand, the
2nd version might actually be faster if FUN is know to return numeric
values only.

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list