# [R] code optimization tips

jim holtman jholtman at gmail.com
Tue Jul 24 01:39:23 CEST 2007

```The quote "what is the problem you are trying to solve" is just part
of my signature.  I used to review projects for performance and
architecture and that was the first question I always asked them.

To pass the argument, if you notice the definition of apply:

apply(X, MARGIN, FUN, ...)

the ... are optional argument, so for your function:

sij <-function(rj,ri,k){
rij=mod(rj-ri)
cos_ij=rj/rij
sin_ij=rj/rij
A<-(1-1i*k*rij)*(3*cos_ij^2-1)*exp(1i*k*rij)/(rij^3)
B<-k^2*sin_ij^2*exp(1i*k*rij)/rij
sij<-A+B
}

you would call apply with the following:

s_ij<-apply(rj,2,sij, ri=ri, k=k)

On 7/23/07, baptiste Auguié <ba208 at exeter.ac.uk> wrote:
>
> On 23 Jul 2007, at 15:19, jim holtman wrote:
>
> > First question is why are you defining the functions within the main
> > function each time?  Why don't you define them once outside?
> >
>
>
> Fair enough!
>
> As said, I'm new to R and don't know whether it is best to define
> functions outside and pass to them all necessary arguments, or nest
> them and get variables in the scope from parents. In any case, I'd
> agree my positions(), mod() and sij() functions would be better
> outside. Here is a corrected version (untested as something else is
> running),
>
> >
> > positions <- function(N) {
> >    reps <- 2*N+1
> >    matrix(c(rep(-N:N, each = reps), rep(-N:N, times = reps)),
> >           nrow = 2, byrow = TRUE)
> > }
>
> > mod<-function(x){sqrt(x^2+x^2)} # modulus
>
> > sij <-function(rj,ri,k){
> > rij=mod(rj-ri)
> > cos_ij=rj/rij
> > sin_ij=rj/rij
> >
> > A<-(1-1i*k*rij)*(3*cos_ij^2-1)*exp(1i*k*rij)/(rij^3)
> > B<-k^2*sin_ij^2*exp(1i*k*rij)/rij
> >
> > sij<-A+B
> > }
>
> > alpha_c <- function(lambda=600e-9,alpha_s=1e-14,N=400,spacing=1e-7){
> >
> > k<-2*pi/lambda
> > ri<-c(0,0) # particle at the origin
> >
> > rj<-positions(N)*spacing # all positions in the 2N x 2N array
> > rj<-rj[1:2,-((dim(rj)-1)/2+1)] # remove rj=(0,0)
> >
> > s_ij<-apply(rj,2,sij)
>
> *** Now, how do I pass k and ri to this function ? ***
>
> > S<-sum(s_ij)
> > alpha_s/(1-alpha_s*S)
> > }
> > alpha_c()
> >
>
>
> >
> > --
> > Jim Holtman
> > Cincinnati, OH
> > +1 513 646 9390
> >
> > What is the problem you are trying to solve?
>
>
> Wondering whether that's part of the signature?
>
> the problem is related to scattering by arrays of particles, more
> specifically to evaluate the array influence on the effective
> polarizability (alpha) of a particle via dipolar radiative coupling.
>
>

--
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

```