Barnaby
Barnaby

Reputation: 1480

Applying rollapply to a writen function or using a loop

This is probably a basic rollapply or loop question, however I can not find a way to instruct the rollapply function or to make an expression for a loop calculation

I have a vector of growth rates with an initial value of 100. I would like to calculate the value at each point of the growth series and obtain a vector of this values. Given that the actual growth series is much longer tan the one below the example below is not possible.

x<-c(0.02,0.01,0.4,0.09,-0.3,0.1)

100*(1+x[1])*(1+x[2])*(1+x[3])*(1+x[4])*(1+x[5])*(1+x[6])#End Value 

a1<-100*(1+x[1])#1st value
a2<-a1*(1+x[2])#2nd value
a3<-a2*(1+x[3])#3rd value
a4<-a3*(1+x[4])#4th value
a5<-a4*(1+x[5])#5th value
a6<-a5*(1+x[6])#6th value

s<-c(a1,a,2,a,3,a4,a,5,a6) #vector of values 

I believe rollapply could be used here, however I can not write the function as to take the prior value and the next sequentially as to create a function and also I am unsure if and how to incorporate the initial value of 100 in the function or adding it at the beguining of x. In addition maybe this can be done as a loop. (Find the function in pseudo code)

x<-c(0.02,0.01,0.4,0.09,-0.3,0.1)

require(zoo);   
fn<- function(y) {(1+prior x)*(1+next x)}
rollapply(x, 1, fun= fn, fill=NA, align='right')

Any help is welcomed

Upvotes: 0

Views: 353

Answers (1)

IRTFM
IRTFM

Reputation: 263311

 x<-c(0.02,0.01,0.4,0.09,-0.3,0.1)

desired <- 100*(1+x[1])*(1+x[2])*(1+x[3])*(1+x[4])*(1+x[5])*(1+x[6])#End Value 
desired
100*tail( cumprod (1+x) , 1)

Oh, dammit. I should have read the comments first. @G.Grothendieck has already been here. I suppose showing how to do it with Reduce could be useful:

> 100*Reduce("*", 1+x)
[1] 121.0506

Upvotes: 1

Related Questions