Possible Duplicate:

Speed up the loop operation inR

I have a few questions regarding loops. I know that **R** works faster with vectorized calculations, and I would like to change the below code to take advantage of this. Looking into some other answers on the forum the sapply function seems to be able to replace the inside for loop, but I am generating a vector of zeros so there is an error. Tao remains 1000, and I think this is creating the problem.

My primary concern is speed, as I need to create a loop around the entire algorithm and plot in different V and n sizes for some further analysis.

Thanks for your help

Alternativeloop

```
tao = 1000
L = (tao - 1)
n = 10
V = 5
I = 10000
V_s = matrix(rnorm(I), I, 1)
V_b = matrix(rnorm(I), I, 1)
signal <- matrix(0, L, 1)
for( j in (n:L)){
sapply(((j-n+1):j),function (tao) signal[j] = signal[j] + abs(V_s[tao] - V_b[tao]))
signal[j] = (signal[j] / (n * V) )
}
```

Original loop

```
tao = 1000
L = (tao - 1)
n = 10
V = 5
I = 10000
V_s = matrix(rnorm(I), I, 1)
V_b = matrix(rnorm(I), I, 1)
signal <- matrix(0, L, 1)
for( j in (n:L)){
for( tao in ((j-n+1):j)) {
signal[j] = (signal[j] + abs(V_s[tao] - V_b[tao]))
}
signal[j] = (signal[j] / (n * V) )
}
```

`browser()`

inside the for(tao) loop, you'll be able to inspect the inner workings of the function and see what's going on. – Roman Luštrik Jan 25 '13 at 10:37Rcode: stackoverflow.com/a/8474941/636656 – Ari B. Friedman Jan 25 '13 at 10:58