Skip to content
Prev 198750 / 398506 Next

avoiding loop

On Sat, 31 Oct 2009, parkbomee wrote:

            
Well, you haven't given us much to work with.

The optimization choices depend on the particulars of your problem, which 
you've not detailed.

It does not take long to run the tapply() code once, so you need to do it 
many times. Right?

If so, you need to say how the structure varies (rendered as DF in David's 
reply) from iteration to iteration in the optimization.

If it turns out that only 'value' changes and that the number of different 
times is not too large, then precomputing suitable indicator matrics may 
help:

  	mat1 <- model.matrix( ~ 0 + factor(time):as.numeric(choice==1),DF)
  	mat2 <- model.matrix( ~ 0 + factor(time), DF )

Inside the optimization use something like

  	with(DF,(value%*%mat1)/(value%*%mat2))

If the structure can change or the number of unique times is large, then 
with so simple a calculation you should probably just inline some C code.

 	http://cran.r-project.org/web/packages/inline/index.html

HTH,

Chuck
Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901