【问题标题】:How to subtract rows in xts with multiple columns如何用多列减去xts中的行
【发布时间】:2017-10-23 05:15:08
【问题描述】:

如何从整个(多行)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

【问题讨论】:

    标签: r xts


    【解决方案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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-27
        • 1970-01-01
        • 2022-07-07
        • 2019-06-28
        • 2020-11-15
        • 1970-01-01
        • 1970-01-01
        • 2014-03-16
        相关资源
        最近更新 更多