将矩阵除以一列

Roc*_*nce 0 r matrix vectorization xts

我有一个多列xts,我想要除以一个xts(当然使用日期作为主键).

有没有办法以矢量化的方式做到这一点?

谢谢

Rei*_*son 8

?sweep(如果我理解你的意思 - 可重复的例子!?):

data(sample_matrix)
sample.xts <- as.xts(sample_matrix, descr='my new xts object')
## create a matrix...
m <- sample.xts[, -1]
## ...and a vector from the sample.xts object
v <- sample.xts[, 1]
## apply sweep
out <- sweep(m, 1, v, "/")
Run Code Online (Sandbox Code Playgroud)

这使:

> class(out)
[1] "xts" "zoo"
> head(out)
               High       Low     Close
2007-01-02 1.001559 0.9982141 1.0015587
2007-01-03 1.003810 1.0000000 1.0033281
2007-01-04 1.000000 0.9968898 0.9982428
2007-01-05 1.000000 0.9969739 0.9992283
2007-01-06 1.000000 0.9973506 0.9987421
2007-01-07 1.001666 0.9972022 0.9972022
Run Code Online (Sandbox Code Playgroud)