[R-SIG-Finance] row-by-row operations on multiple xts matrices

Murali.MENON at fortisinvestments.com Murali.MENON at fortisinvestments.com
Mon Nov 23 16:41:30 CET 2009


Thanks, Josh. rowSums! So clear and, suddenly, so obvious.
I really need a vacation...
Murali 

-----Original Message-----
From: Joshua Ulrich [mailto:josh.m.ulrich at gmail.com] 
Sent: 23 November 2009 15:34
To: MENON Murali
Cc: r-sig-finance at stat.math.ethz.ch
Subject: Re: [R-SIG-Finance] row-by-row operations on multiple xts matrices

Murali,

Try:
> x <- a*b
> (y <- xts(rowSums(x),index(x)))
           [,1]
1970-01-03  134
1970-01-04  172
1970-01-05  214
1970-01-06  260

HTH,
Josh
--
http://www.fosstrading.com



On Mon, Nov 23, 2009 at 9:25 AM,  <Murali.MENON at fortisinvestments.com> wrote:
> Folks,
>
> If I have two xts objects with some dates in common, and I want to 
> compute, say, the sum of products of their corresponding rows, what is 
> a good way of achieving it?
>
>> a <- xts(matrix(1:10,ncol=2), as.Date(1:5)) b <- 
>> xts(matrix(11:20,ncol=2), as.Date(2:6))
>
> Were these matrices, I could just do something like (inefficiently):
>
>> diag(a %*% t(b))
>
> but that doesn't work here, because the transpose t() function removes 
> the xts-ness of b, and the multiplication occurs row-by-row without 
> date correspondence.
>
> Is there a better way to achieve this than:
>
> # First extract common indices
>> aa <- a[index(a) %in% index(b)]
>> bb <- b[index(b) %in% index(a)]
>
> # Then use the common index to construct a new xts object
>> xts(diag(aa %*% t(bb)), index(aa))
>
>           [,1]
> 1970-01-03  134
> 1970-01-04  172
> 1970-01-05  214
> 1970-01-06  260
>
> I think there's something obvious I'm missing...
>
> Thanks,
>
> Murali
>
> _______________________________________________
> 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