[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:25:48 CET 2009
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
More information about the R-SIG-Finance
mailing list