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

Gabor Grothendieck ggrothendieck at gmail.com
Wed Nov 25 13:36:39 CET 2009


Your example has an index not supported by xts so I will assume your
object is a zoo object.  All xts objects are zoo objects anyways.  If
your actual data has a different class of index than shown here then
the code below should also work with xts.

Try Reduce.  Note that if your real data is large this might not be very fast.

> library(zoo)
> x <- zoo(cbind(c1 = 1:5, c2 = 1:5))
> f <- function(acc, x) sum(x) / acc
> x$c3 <- Reduce(f, split(coredata(x), time(x)), 1, acc = TRUE)[-1]
> x
  c1 c2       c3
1  1  1 2.000000
2  2  2 2.000000
3  3  3 3.000000
4  4  4 2.666667
5  5  5 3.750000


On Tue, Nov 24, 2009 at 11:38 PM, Jiri Hoogland <jiri.hoogland at gmail.com> 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