简体   繁体   中英

R: How to calculate regressive without for-loop

set.seed(1)
n <- 100
ret <- rnorm(n, 0, 0.02)
ret[1] <- 0
price <- cumprod(1+ret)*100
maxi <- 0
drawdown <- rep(0, n)

for (i in 1 : n){
    maxi <- max(price[1 : i])
    drawdown[i] <- price[i] / maxi - 1
}

Hello,

Is it possible to speedup this calculation? Maybe remove the for-loop?

Regards

R has a vectorised cummax function, and division and addition operations are also vectorised, so you can do:

price/cummax(price) - 1

Comparing efficiency when n <- 10000 :

library(microbenchmark)
microbenchmark(
  OP= {
    drawdown <- rep(0, n)
    for (i in 1 : n){
      maxi <- max(price[1 : i])
      drawdown[i] <- price[i] / maxi - 1
    }
  },
  me={
    drawdown2 <- price/cummax(price) - 1
  }, times=10)

# Unit: microseconds
#  expr        min         lq        mean     median         uq        max neval
#    OP 456216.519 483387.361 536067.7521 550912.471 565453.555 663352.635    10
#    me     98.075    102.067    107.5978    105.203    112.331    127.726    10

identical(drawdown, drawdown2)
# [1] TRUE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM