将xts对象中的所有列乘以另一个单列xts对象

时间:2012-08-03 03:50:20

标签: r xts

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

*.default(x,y)中给出错误:不一致的数组

我想要的是将x中的每一列乘以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

理想情况下,解决方案应在index(x)!=index(y)

时有效

ASIDE: 我想出了这个黑客:

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

它适用于测试数据,但在我的真实数据上,它抱怨数组中的错误(ans,c(len.a%/%d2,d.ans),if(!all(vapply(dn) .ans,is.null,'dimnames'[1]的长度不等于数组范围 (我还没有在一小段测试数据中重现这一点。)

Joshua和DWin的答案没有这个问题,因此不仅简洁而且结果质量优越!

3 个答案:

答案 0 :(得分:3)

如果只删除单列xts对象的尺寸,它应该可以工作。然后R的回收规则可以接管。这比DWin's solution略好,因为如果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

答案 1 :(得分:3)

不像JoshuaUlrich's answer那么光滑,但为了展示不同的东西,你可以使用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 :(得分:2)

将y对象转换为普通向量:

> 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