I thought the "apply" functions are faster than for loops, but my most
recent test shows that apply actually takes a significantly longer than a
for loop.  Am I missing something?

It doesn't matter much if I do column wise calculations rather than row wise

## Example of how apply is SLOWER than for loop:

#rm(list=ls())

## DEFINE VARIABLES
mu=0.05 ; sigma=0.20 ; dt=.25 ; T=50 ; sims=1e5
timesteps = T/dt

## MAKE PHI AND DS
phi = matrix(rnorm(timesteps*sims), nrow=sims, ncol=timesteps)
ds = mu*dt + sigma * sqrt(dt) * phi

## USE APPLY TO CALCULATE ROWWISE CUMULATIVE PRODUCT
system.time(y1 <- apply(1+ds, 1, cumprod))
## UNTRANSFORM Y1, BECAUSE ROW APPLY FLIPS THE MATRIX
y1=t(y1)

## USE FOR LOOP TO CALCULATE ROWWISE CUMULATIVE PRODUCT
y2=matrix(NA,nrow(ds),ncol(ds))
system.time(
    for (i in 1:nrow(ds)){
        y2[i,]<-cumprod(1+ds[i,])
    }
)

## COMPARE RESULTS TO MAKE SURE THEY DID THE SAME THING
str(y1)
str(y2)
all(y1==y2)

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org 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