[R] Loops that last for ever...

Constantine Tsardounis costas.magnuse at gmail.com
Mon Jan 30 18:41:11 CET 2006

Hello, good morning or evening!...

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])

Of course the functions I actually call are more complicated,
increasing the total time of calculations to a lot of minutes,...

<< 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

demands more than 50 lines at the beginning of the script that
"initiate" the lists (e.g.
example.list.1 <- list()
example.list.2 <- list()
example.list.50 <- list()

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

Thank you very very much in advance,

Constantine  Tsardounis

More information about the R-help mailing list