[R] sequential for loop

Michael Toews mwtoews at sfu.ca
Fri Apr 20 06:31:12 CEST 2007


Hi all,

I'm usually comfortable using the *apply functions for vectorizing loops 
in R. However, my particular problem now is using it in a sequential 
operation, which uses values evaluated in an offset of the loop vector. 
Here is my example using a for loop approach:

dat <- data.frame(year=rep(1970:1980,each=365),yday=1:365)
dat$value <- sin(dat$yday*2*pi/365)+rnorm(nrow(dat),sd=0.5)
dat$ca <- dat$cb <- 0 # consecutive above and below 0

for(n in 2:nrow(dat)){
  if(dat$value[n] > 0)
    dat$ca[n] <- dat$ca[n-1] + 1
  else
    dat$cb[n] <- dat$cb[n-1] + 1
}

I'm inquiring if there is a straightforward way to vectorize this (or a 
similar example) in R, since it gets rather slow with larger data 
frames. If there is no straightforward method, no worries.

Thanks in advance.
+mt



More information about the R-help mailing list