[R] any alternatives for complex for-loops?

Erik Iverson iverson at biostat.wisc.edu
Wed Nov 12 06:59:09 CET 2008


Well, in this case, you're simply applying a rolling mean with window of 
2.  Package 'zoo' has the rollmean function that does exactly this sort 
of thing

x <- 1:10
rollmean(x, 2)

Then, check out the source for rollmean by simply typing


at the R prompt.  See how they did it. I realize not a direct answer to 
your question, but hopefully gets you started.  You'll have to think 
about it on a case by case basis in general.


Kinoko wrote:
> Thanks for the replies
> Sorry for being unclear.
> I am asking if there is a way to process a vector in a way
> that uses references to other elements of the same vector.
> And doing this without a for-loop.
> Here is a running code:
> <code>
  complexFn <- function(a,b){
    c <- (a+b)/2

  x <- 1:10
  y <- rep(NA, length(x))

  for (i in 1:length(x)){
          y[i] = complexFn(x[i-1], x[i])

> And here is another attempt without the for-loop.
> <code>
> x <- 1:10
> x1 <- c(NA, x)
> length(x1)<-length(x)
> y<-mapply(complexFn,x,x1)
> print(c(y))
> </code>
> If someone could tell me the normal/elegant/effective/R way of
> doing this kind of vector processing, that would highly appreciated.
> best,
> gabor
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list