[R] any alternatives for complex for-loops?

Kinoko andzsinszan at gmail.com
Wed Nov 12 09:32:21 CET 2008

Dear Erik,

Thank you very much.
Probably it is exactly "zoo" what I have beenlooking for.
Actually "rollapply" looks like something I could use, but...

For some reasons beyond me, the following attempts
in which I tried to apply my home-made 'fun' to rollaply
miserable failed.

complexFn <- function(a,b){
  c <- (a+b)/2

x <- zoo(1:10)

# OK with built in function
rollapply(x,width=2, complexFn)
rollapply(x,width=2, "complexFn")
rollapply(x,width=2, FUN=complexFn)
rollapply(x,width=2, FUN<-function(a,b){(a+b)/2} )
rollapply(x,width=2, FUN<-function(a,b) complexFn)

However when I rewrote my fn to have only one argument, rollapply
works fine.

complexFn <- function(ab){
  a <- ab[1]
  b <- ab[2]
  c <- (a+b)/2
x <- zoo(1:10)
rollapply(x,width=2, complexFn)

Now, it would be nice to figure out how to use rollapply with my
original two-argument function.
(surely I dont want to rewrite all of my references to complexFn... ).

R being an OO language I would have a look at overloading
(well... for the first glance overloading is not as straightforward as
in Java or C++).

Of course the easiest thing would be to make rollaply work with my two-
argument function.
I am sure it is pretty easy... for people who already know it...

More information about the R-help mailing list