[R] cumsum over varying column lengths

Murali Menon feanor0 at hotmail.com
Fri Mar 16 19:15:36 CET 2007


Folks,

I have a matrix of historicalReturns, where entry (i, j) is the daily return 
corresponding to date i and equity j. I also have a matrix startOffset, 
where entry (1, k) is the row offset in historicalReturns where I entered 
into equity k.

So we have that NCOL(startOffset) = NCOL(historicalReturns).

Now I would like compute for each column in historicalReturns, the 
cumulative return 'returnsFromInception' for the equity starting from the 
startOffset date.

Is there a better way than as follows:


n <- NROW(historicalReturns)
returnsFromInception <- matrix(nrow = 1, ncol = 
NCOL(historicalInceptionDates))

for (i in 1 : NCOL(historicalReturns))
{
    cumReturn <- cumsum(historicalReturns[startOffset[1, i] : n, i])
    returnsFromInception[1, i] <- cumReturn[length(cumReturn)]
}

This works for me, but seems rather inelegant, and I don't like having to 
use a matrix for returnsFromInception and startOffset, where vectors would 
work.

Thanks for your help.

Murali

_________________________________________________________________
It’s tax season, make sure to follow these few simple tips



More information about the R-help mailing list