Q:

R - speed up R version of MATLAB for incremental loop

Is there any way to speed up the following R translation of the MATLAB for loop below?
Although this example is small, the real data set may have up to 500,000 rows for SSC, SSL, and dt. Plus this similar operation will have to be applied to about 20 data sets.
SSC <- abs(rnorm(1000))
SSL <- abs(rnorm(1000))
dt <- rep(15, 1000)

for (i in 2:length(SSC))
{
TSSL[[i-1]] <- (SSL[i] + SSL[i-1])/(2*60*dt[i-1])
}

# MATLAB code
# for i=2:length(SSC)
# TSSL(i-1)=(SSL(i) + SSL(i-1))/2*60*dt(i-1);
# end

Thank you.

A:

what is TSSL? You should initialize it.
Also you dont' need a loop here, you should instead use vector operations:
N    <- 1000
SSC  <- abs(rnorm(N))
SSL  <- abs(rnorm(N))
dt   <- rep(15, N)
TSSL <- rep(NA,N)

TSSL[1:(N-1)] = (SSL[2:N]+SSL[1:(N-1)])/(2*60*dt[1:(N-1)])

I strongly recommend reading Chapter 3 "Failing to vectorize" of R inferno.

