Is there a way to implement this faster than doing it in a loop. for (i in length(settle)-1:1) { settle[i] = settle[i+1]/(1 + settle.pct[i+1]) } I want to guarantee that i+1 is calculated before i
On Wed, 11 May 2005 13:05:58 -0400 Omar Lakkis wrote:> Is there a way to implement this faster than doing it in a loop. > > for (i in length(settle)-1:1) { > settle[i] = settle[i+1]/(1 + settle.pct[i+1]) > } > > I want to guarantee that i+1 is calculated before iYes, as the loop above as only one iteration, you can easily do it as: n <- length(settle) settle[n-1] <- settle[n]/(1 + settle.pct[n]) What you probably really meant, can also be simply done without a for loop. You need a vector settle.pct and a scalar starting value (not a full vector) settle. So in the following settle is assumed to be only settle[n]: settle/c(rev(cumprod(1 + rev(settle.pct)))[-1], 1) If settle.pct should in fact also be only be constant, this can of course be further simplified. Z> ______________________________________________ > 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 >
It is, backwards, a cumulative product so you could use cumprod. On Wed, 11 May 2005, Omar Lakkis wrote:> Is there a way to implement this faster than doing it in a loop. > > for (i in length(settle)-1:1) { > settle[i] = settle[i+1]/(1 + settle.pct[i+1]) > } > > I want to guarantee that i+1 is calculated before i > > ______________________________________________ > 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 >-- Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595
Omar Lakkis wrote:> Is there a way to implement this faster than doing it in a loop. > > for (i in length(settle)-1:1) { > settle[i] = settle[i+1]/(1 + settle.pct[i+1]) > }You dont need a loop at all here. How so? Well, as it is written the code in the for loop only executes once: > settle=1:10 > for (i in length(settle)-1:1) { + print(i) + } [1] 9 > you have made a mistake, and I think you really want: > for (i in (length(settle)-1):1 ) { since R does the ':' first and then does 'length(settle)-' unless you bracket it: > length(settle)-1:1 [1] 9 > (length(settle)-1):1 [1] 9 8 7 6 5 4 3 2 1 I don't see an obvious way to get rid of the for loop though... Baz