2014-10-29 54 views
2
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 
} 

你好,R:如何在沒有計算迴歸for循環

是否可以用來加快該如何計算?也許刪除for循環?

問候

回答

6

R的矢量化cummax功能,分工和另外操作也矢量化,所以你可以做:

price/cummax(price) - 1 

比較效率時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