[R] Loops that last for ever...

Liaw, Andy andy_liaw at merck.com
Mon Jan 30 20:40:30 CET 2006


From: Constantine Tsardounis
> 
> 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
> [[1]]
> [1]........................[1000]
> [[2]]
> [1]........................[840]
> ...
> [[50]]
> [1]........................[945]
> 
> 
> 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])
> 			}
> 		}
> }

For this you want to vectorize the computation inside, eliminating the j
loop, then use lapply() if you like for the outer loop.  That saves you the
line to initialize the list.
 
> 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?

Yes, by putting them all in one list.

Andy
 
> 
> Thank you very very much in advance,
> 
> Constantine  Tsardounis
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
>




More information about the R-help mailing list