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
[EMAIL PROTECTED]
+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
>
>______________________________________________
>[email protected] 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.
>
>
>  
>

______________________________________________
[email protected] 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.

Reply via email to