Skip to content
Prev 236790 / 398500 Next

Help with apply

Hi,

It seemed to me like the calculations were implemented in a bit of a
redundant way, so I tried to simplify it algebraically.  doit1 is
Phil's version of your original calculations, and doit2 is my
simplified way.

doit1 <- function(i, j) {
  exp(sum(log((exp(tmp[i,] * (qq$nodes[j]-b)))/
              (factorial(tmp[i,])*exp(exp(qq$nodes[j]-b))))))*
  ((1/(s*sqrt(2*pi)))*exp(-((qq$nodes[j]-0)^2/(2*s^2))))/
  dnorm(qq$nodes[j])*qq$weights[j]
}

doit2 <- function(i, j) {
  (prod(exp((tmp[i,]*(qq$nodes[j]-b))-exp(qq$nodes[j]-b))/
        factorial(tmp[i,]))*qq$weights[j])/
  (s*sqrt(2*pi)*dnorm(qq$nodes[j])*exp((qq$nodes[j]-0)^2/(2*s^2)))
}

system.time(t(outer(1:300,1:2,Vectorize(doit1))))
system.time(t(outer(1:300,1:2,Vectorize(doit2))))


New vs. Old
Characters (for the calculations):
154 vs. 177
Function calls for calculations (i.e., excluding subseting/dnorm, etc.):
22 vs. 27

Timing difference:
Not appreciable on my system, but I spent so long wading through
exactly what was happening, I figured why not share it.  Moving tmp up
to 300 rows, I got:
user  system elapsed
  9.044   0.008  10.135
user  system elapsed
  8.413   0.008   8.893

At this rate, the difference between a few million rows might save you
enough time you can stretch your hands once, and those 20 characters
should really free up space on your hard disk....sigh.

Josh
On Mon, Oct 4, 2010 at 11:22 AM, Doran, Harold <HDoran at air.org> wrote: