如何用多列减去xts中的行

How to subtract rows in xts with multiple columns

如何从整个(多行)xts 对象中减去 xts 对象中的单行数据?

MWE

require(xts)
data(sample_matrix)
x <- as.xts(sample_matrix)
x-coredata(x['2007-06-09'])[1,]

从输出中,R 已获取行向量,剥离其上下文,并通过跨列循环将其减去。

例如如果我使用以下 xts 对象代替 x

a1 b1 c1 d1
a2 b2 c2 d2

并做了下面的减法

x-coredata(x[2,])[1,]

结果会是

a1-a2 b1-c2 c1-a2 d1-c2 
a2-b2 b2-d2 c2-b2     0

我的预期输出:

a1-a2 b1-b2 c1-c2 d1-d2
    0     0     0     0

由于 xts 继承自 zoo,它在底层有一个数字矩阵,我们可以利用所有常用的 matrix 操作:

library(xts)
set.seed(911)
myXts <- xts(cbind(rnorm(5), rnorm(5)), seq(as.Date("2017-10-22"), length.out = 5, by = 1))

myXts - 5 # subtracts 5 from every cell
sweep(myXts, 2, c(5, 1)) # subtracts 5 from col 1, and 1 from col 2 (all rows)
myXts[2, ] <- myXts[2, ] - c(5, 1) # subtract only from row 2 and replace the existing

您可以使用scale()

data(sample_matrix)
x <- tail(as.xts(sample_matrix), 5)

scale(x, center=unlist(tail(x, 1)), scale=FALSE)

#                    Open       High         Low      Close
# 2007-06-26 -0.231679339 -0.3251569 -0.23167934 -0.1510840
# 2007-06-27 -0.051446746 -0.2245367 -0.07452939 -0.1395032
# 2007-06-28  0.001354599 -0.2366639 -0.10227449 -0.1600355
# 2007-06-29 -0.038391981 -0.1656322 -0.05735147 -0.1024815
# 2007-06-30  0.000000000  0.0000000  0.00000000  0.0000000