[R] Loops that last for ever...
Constantine Tsardounis
costas.magnuse at gmail.com
Tue Jan 31 00:50:56 CET 2006
Thank you very very much for your responses...
How exactly do I vectorize?
> > 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.
More information about the R-help
mailing list