# [R] Loops that last for ever...

From: Constantine Tsardounis <costas.magnuse_at_gmail.com>
Date: Tue 31 Jan 2006 - 04:41:11 EST

After studying some of the examples at S-poetry Document, I tried to implement some of the concepts in my R script, that intensively uses looping constructs. However I did not manage any improvement. My main problem is that I have a list of a lot of data e.g.:
> xs

```[]
........................
[]
........................
```

...
[]
```........................

```

Having a script with loops inside loops (for example in a Monte-Carlo simulation) takes a lot of minutes before it is completed. Is there another easier way to perform functions for each of the [[i]] ? Using probably apply? or constructing a specific function? or using the so-called "vectorising" tricks?

One example could be the following, that calculates the sums 1:5, 2:6, 3:7,..., for each of xs[[i]] :

xs <- lapply(1:500, function(x) rnorm(1000)) totalsum <- list()
sums <- list()
first <- list()

for(i in 1:length(xs)) {
totalsum[i] <- sum(xs[[i]])

```	for(j in 1:length(xs[[i]])) {
if(j == 1) {
sums[[i]] <- list()
}
if(j >= 5) {
sums[[i]][j] <- sum(xs[[i]][(j-4):j])
}
}
```

}

<< 1 >>. How could I optimize (or better eliminate?...) the above loop? Any other suggestions for my scripting habits?

Another problem that I am facing is that calculating a lot of lists (>50), that contain results of various econometric tests of all the variables, in the form of

example.list[[i]] <- expression

<< 2 >>. Is there a way to avoid that?

Thank you very very much in advance,

Constantine Tsardounis

R-help@stat.math.ethz.ch mailing list