[R-SIG-Finance] how use the results of rollapply in the previousrow to the next row...

Benczik Sandor sandor.benczik at crabel.ro
Wed Nov 25 12:59:52 CET 2009


Hi Jiri,

I found that problems with recursive definitions involving multiple
vectors/columns are usually next to impossible to tackle without for
loops, or without rewriting the formula in a non-recursive way. For your
case here is a kludge:

> a <- data.frame(c1 = 1:5, c2 = 1:5)
> sum.col <- apply(a, 1, sum)
> norms <- exp(c(1,-1) * cumsum(c(1,-1)*log(sum.col)))
Warning messages:
1: In c(1, -1) * log(sum.col) :
  longer object length is not a multiple of shorter object length
2: In c(1, -1) * cumsum(c(1, -1) * log(sum.col)) :
  longer object length is not a multiple of shorter object length
> sum.col / c(1, norms[-length(norms)])
[1] 2.000000 2.000000 3.000000 2.666667 3.750000

HTH,
Sandor

PS. I think the generally accepted view is that such questions belong to
the general R-help list, not being related to finance.

On Wed, 2009-11-25 at 06:38 +0200, Jiri Hoogland wrote:
> Hi,
> 
> say I have a xts object x with data I want to apply a function f over
> row by
> row (by.column=F)
> 
> x =
> index c1 c2  c3
> 1       1   1    0
> 2       2   2    0
> 3       3   3    0
> 4       4   4    0
> 5       5   5    0
> 
> what i would like to do and i am not sure that that is possible is the
> following
> 
> the result of operating on one row is put in the last column of x of
> that
> same row
> and is used in the operation on the next row, where f is some
> non-trivial
> function of the columns
> 
> So for example the simple function summing over the row
> and normalizing by the previous value of the last columns value in the
> previous row
> (first row does not normalize here)
> 
> x =
> index c1 c2   c3
> 1       1   1    2      = 1+1
> 2       2   2    2      = 2/2+2/2 = 2
> 3       3   3    3      = 3/2+3/2 = 3
> 4       4   4    8/3   = 4/3+4/3
> 5       5   5    15/4 = 5/8*3+5/8*3
> 
> Is there some way to sneak this into rollapply?
> Maybe I am asking too much, but if somebody
> can enlighten it would be greatly appreciated
> Thanks!
> Jiri
> 
>         [[alternative HTML version deleted]]
> 
> _______________________________________________
> R-SIG-Finance at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-sig-finance
> -- Subscriber-posting only.
> -- If you want to post, subscribe first.
> 
>



More information about the R-SIG-Finance mailing list