[R] For loops

Patrick Burns pburns at pburns.seanet.com
Thu Jul 26 10:17:51 CEST 2007


Any time you are calling a function one value at a time,
it is worth asking if you can eliminate a loop (or more).

If 'G.fun' is vectorized in its first argument, then you can
easily get rid of the three inner loops.  Just generate a
vector of all of the values and do:

gj <- sum(G.fun(long.vector, ff))

If 'G.fun' is not vectorized and can't be vectorized, then
you might save some time by still creating a vector of the
first argument first.  Whether that will be a significant
reduction depends on how time consuming 'G.fun' is.

There is a caveat.  If 'n' is large, then you could create a
vector that strains the amount of memory (RAM) that you
have.  If that is the case, then there will be some compromise
between loops and vectorization that will be optimal.

Patrick Burns
patrick at burns-stat.com
+44 (0)20 8525 0696
http://www.burns-stat.com
(home of S Poetry and "A Guide for the Unwilling S User")

Joaquim J. S. Ramalho wrote:

>Hi,
>
>is there a way of simplifying the following code:
>
>G <- rep(NA,n)
>
>for(i in 1:n)
>{
>gj <- 0
>for(j in 1:n)
>{
>for(l in 1:n)
>{
>for(m in 1:n)
>{
>gj <- gj+G.fun(XB[i]+p[3]*X[j,3]+p[4]*X[l,4]+p[5]*X[m,5],ff)
>}
>}
>}
>G[i] <- gj/n^3
>}
>
>Thanks.
>
>Joaquim Santos
>
>______________________________________________
>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
>and provide commented, minimal, self-contained, reproducible code.
>
>
>  
>



More information about the R-help mailing list