如何使用多列减去xts中的行

时间:2017-10-22 20:39:35

标签: r xts

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

MWE

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

从输出中,R取出了行向量,去掉了它的上下文,并通过回收列来减去它。

E.g。如果我使用以下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

2 个答案:

答案 0 :(得分:1)

由于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

答案 1 :(得分:1)

您可以使用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