3
votes
library(xts)
set.seed(1)
x = xts( cbind(a=1:10,b=20:11) , Sys.Date()+1:10 )
y = xts( runif(10) , Sys.Date()+1:10 )
z = x*y

Gives me Error in *.default(x, y) : non-conformable arrays

What I want is to multiply each column in x by the value in y.

Expected result:

                   a         b
2012-08-04 0.2655087  5.310173
2012-08-05 0.7442478  7.070354
2012-08-06 1.7185601 10.311361
2012-08-07 3.6328312 15.439532
2012-08-08 1.0084097  3.226911
2012-08-09 5.3903381 13.475845
2012-08-10 6.6127269 13.225454
2012-08-11 5.2863823  8.590371
2012-08-12 5.6620264  7.549369
2012-08-13 0.6178627  0.679649

Ideally the solution should work when index(x)!=index(y)

ASIDE: I came up with this hack:

 z = xts( apply(x,2,function(col) col*y ) , index(x) )

It works on the test data, but on my real data it complains with Error in array(ans, c(len.a%/%d2, d.ans), if (!all(vapply(dn.ans, is.null, : length of 'dimnames' [1] not equal to array extent (I've not managed to reproduce this in a small piece of test data yet.)

The answers by Joshua and DWin do not have this problem, so are superior not just in succinctness but also in quality of results!

3

3 Answers

4
votes

It should work if you just drop the dimensions of the single-column xts object. Then R's recycling rules can take over. This is slightly better than DWin's solution because it will work correctly if index(x) != index(y).

R> (z <- x*drop(y))
                   a         b
2012-08-03 0.2655087  5.310173
2012-08-04 0.7442478  7.070354
2012-08-05 1.7185601 10.311361
2012-08-06 3.6328312 15.439532
2012-08-07 1.0084097  3.226911
2012-08-08 5.3903381 13.475845
2012-08-09 6.6127269 13.225454
2012-08-10 5.2863823  8.590371
2012-08-11 5.6620264  7.549369
2012-08-12 0.6178627  0.679649
R> (z1 <- x*drop(y[1:5]))
                   a         b
2012-08-03 0.2655087  5.310173
2012-08-04 0.7442478  7.070354
2012-08-05 1.7185601 10.311361
2012-08-06 3.6328312 15.439532
2012-08-07 1.0084097  3.226911
3
votes

Not quite as slick as JoshuaUlrich's answer, but for the sake of showing something different, you can use sweep

sweep(x, 1, y, "*")
#                   a         b
#2012-08-04 0.2655087  5.310173
#2012-08-05 0.7442478  7.070354
#2012-08-06 1.7185601 10.311361
#2012-08-07 3.6328312 15.439532
#2012-08-08 1.0084097  3.226911
#2012-08-09 5.3903381 13.475845
#2012-08-10 6.6127269 13.225454
#2012-08-11 5.2863823  8.590371
#2012-08-12 5.6620264  7.549369
#2012-08-13 0.6178627  0.679649
2
votes

Turn the y object into an ordinary vector:

> z <-  x * c(coredata(y))
> z
                      a             b
2012-08-03 0.2655086631  5.3101732628
2012-08-04 0.7442477993  7.0703540931
2012-08-05 1.7185600901 10.3113605403
2012-08-06 3.6328311600 15.4395324299
2012-08-07 1.0084096552  3.2269108966
2012-08-08 5.3903381098 13.4758452745
2012-08-09 6.6127268802 13.2254537605
2012-08-10 5.2863823399  8.5903713023
2012-08-11 5.6620263951  7.5493685268
2012-08-12 0.6178627047  0.6796489751