I have an xts
object, and I wish to create weighted sums of the columns (and do this a LOT). By far the easiest way is matrix multiplication, but then the result loses the nice xts
qualities.
It's easy to add them back by creating a new xts
object -- but it's both slow and tedious.
For example:
dd <- xts(matrix(rnorm(200), ncol=2), Sys.Date() + 1:100)
w_sum <- dd %*% c(-1, 1)
... and the problem is:
> tail(w_sum)
[,1]
[95,] 0.1758262
[96,] -0.3310975
[97,] -0.1204836
[98,] -1.2242001
[99,] -1.7333222
[100,] 1.1216603
The fix is:
w_sumx <- xts(dd %*% c(-1, 1), index(dd))
But not only is it bothersome, it's slow. Also, i note with interest that xts
is really fast for subtraction. Is there a way to do this which leverages the fast internals of xts
?
f1 <- function() xts(dd %*% c(-1, 1), index(dd))
f2 <- function() dd[,2] - dd[,1]
> microbenchmark::microbenchmark(f1(), f2(), times = 1000)
Unit: microseconds
expr min lq mean median uq max neval cld
f1() 83.7 97.3 114.1294 104.65 115.00 6688.4 1000 b
f2() 26.3 34.0 40.6202 38.85 45.15 155.4 1000 a