R: How to calculate regressive without for-loop -



R: How to calculate regressive without for-loop -

set.seed(1) n <- 100 ret <- rnorm(n, 0, 0.02) ret[1] <- 0 cost <- cumprod(1+ret)*100 maxi <- 0 drawdown <- rep(0, n) (i in 1 : n){ maxi <- max(price[1 : i]) drawdown[i] <- price[i] / maxi - 1 }

hello,

is possible speedup calculation? maybe remove for-loop?

regards

r has vectorised cummax function, , partition , add-on operations vectorised, can do:

price/cummax(price) - 1

comparing efficiency when n <- 10000:

library(microbenchmark) microbenchmark( op= { drawdown <- rep(0, n) (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

r for-loop

Comments

Popular posts from this blog

php - How to pass multiple values from url -

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

database - php search bar when I press submit with nothing in the search bar it shows all the data -