[R] cumulative growth rates indexed to a common starting point over n series of observations

Dirk Eddelbuettel edd at debian.org
Fri Sep 1 23:07:35 CEST 2006


On 1 September 2006 at 14:59, Dirk Eddelbuettel wrote:
| 
| On 1 September 2006 at 14:30, toby_marks at americancentury.com wrote:
| | The apply with the cumprod was exactly what I was after.  The apply just 
| | wasn't clicking with me, and I had overlooked the cumprod.  Thanks to all 
| | for pushing me down the right path!
| | 
| | Actually, what I am ultimately after is a way to link this series, without 
| | having to use a for loop ( the only way I can think of ... ).  But, would 
| | like to see if it can be linked  using mapply or apply against the rows 
| | and to compute the linked results. 
| | 
| | zz = matrix(rnorm(20), ncol=2)
| | zzcum = apply(zz/100 + 1, 2, cumprod)
| | zzlinkcum = 100*zzcum
| | for(i in 2:length(zz[,1])){ zzlinkcum[i,]=zzlinkcum[i-1,]*zzcum[i,]}  ### 
| | Is there a better way here ?
| 
| Sure, why not call apply again?
| 
| > set.seed(42); zz <- matrix(rnorm(20), ncol=2)
| > zzcum <- apply(1+zz/100, 2, cumprod)
| > apply(rbind(c(1,1), zzcum), 2, cumprod)*100

Small mistake, that compounds twice. You probably want

> set.seed(42)
> zz <- matrix(rnorm(20), ncol=2)
> apply( rbind(c(1,1), zz/100+1), 2, cumprod)*100
          [,1]      [,2]
 [1,] 100.0000 100.00000
 [2,] 101.3710 101.30487
 [3,] 100.7985 103.62135
 [4,] 101.1645 102.18220
 [5,] 101.8048 101.89732
 [6,] 102.2163 101.76147
 [7,] 102.1079 102.40863
 [8,] 103.6512 102.11753
 [9,] 103.5531  99.40482
[10,] 105.6433  96.97888
[11,] 105.5770  98.25911
> 

Hth, Dirk

-- 
Hell, there are no rules here - we're trying to accomplish something. 
                                                  -- Thomas A. Edison



More information about the R-help mailing list