Can this be re-implemented to run faster (without the loop) ?
r <- list()
n = nrow(prices)
for (i in (w+1):n) {
window <- prices[(i-w):(i-1),]
if (prices[i,]$settle > max(window$high)) r <-
append(r, 1)
else if (prices[i,]$settle < min(window$low)) r <-
append(r, -1)
}
without the loop
3 messages · Omar Lakkis, Giovanni Petris, Gabor Grothendieck
I won't go into the details of your loop, but in general it is usually better, if possible, to create a list of the appropriate length upfront. Giovanni
Date: Fri, 13 May 2005 16:58:42 -0400
From: Omar Lakkis <uofiowa at gmail.com>
Sender: r-help-bounces at stat.math.ethz.ch
Precedence: list
DomainKey-Signature: a=rsa-sha1; q=dns; c=nofws; s=beta; d=gmail.com;
Can this be re-implemented to run faster (without the loop) ?
r <- list()
n = nrow(prices)
for (i in (w+1):n) {
window <- prices[(i-w):(i-1),]
if (prices[i,]$settle > max(window$high)) r <-
append(r, 1)
else if (prices[i,]$settle < min(window$low)) r <-
append(r, -1)
}
______________________________________________ R-help at stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
__________________________________________________ [ ] [ Giovanni Petris GPetris at uark.edu ] [ Department of Mathematical Sciences ] [ University of Arkansas - Fayetteville, AR 72701 ] [ Ph: (479) 575-6324, 575-8630 (fax) ] [ http://definetti.uark.edu/~gpetris/ ] [__________________________________________________]
On 5/13/05, Omar Lakkis <uofiowa at gmail.com> wrote:
Can this be re-implemented to run faster (without the loop) ?
r <- list()
n = nrow(prices)
for (i in (w+1):n) {
window <- prices[(i-w):(i-1),]
if (prices[i,]$settle > max(window$high)) r <-
append(r, 1)
else if (prices[i,]$settle < min(window$low)) r <-
append(r, -1)
}
Given the complex looping it would be better if you provided documentation with your post and a reproducible example, not just a code snippet. See the posting guide. At any rate, it seems that what you want to do is to append 1 whenever the settle price exceeds the high of the last w time points and a -1 whenever the settle price is below the low of the last w time points. Represent the prices as a zoo series with 3 columns: high, low, settle and use the following (untested) loop-free code: high <- 1; low <- 2; settle <- 3 W <- w+1 r <- rapply(prices, W, function(x) sign(x[W,settle] > max(x[-W,high])) - (x[W,settle] < min(x[-W,low])), by.column = FALSE, align = "right") ) r[r!=0]