在xts中添加元素

Add elements in xts

我正在将我的脚本转换为使用 xts 而不是数据框,但无法对不同行/列中的元素进行计算。

实际上,我使用 for 循环遍历 df 行,并根据计算使用 if-elses。

但是,为了简化问题,我可以在 df 中添加 Col A Row 1 和 Col B Row 2 就好了,但在 xts 中不行....这是一些示例代码:

> df <- data.frame(c(1:3),c(4:6))
> names(df) <- c('colA','colB')
> df
  colA colB
1    1    4
2    2    5
3    3    6
> df$colA[1] + df$colB[2]
[1] 6
> 
> 
> library(xts)
> x <- xts(df, order.by=as.Date(1:3))
> x
           colA colB
1970-01-02    1    4
1970-01-03    2    5
1970-01-04    3    6
> x$colA[1] + x$colB[2]
Data:
integer(0)

Index:
numeric(0)
> 

有什么想法可以让它发挥作用吗?

当添加两个 xts 对象时,它们被合并以对齐时间,然后添加。第 1 行和第 2 行没有公共索引,因此合并生成一个空对象。

这里有一些备选方案:

1) [[ 单个 [ 将 return 另一个 xts 对象,但 [[ 不会因此避免问题:

x$colA[[1]] + x$colB[[2]]
## [1] 6

2) coredata 在添加之前尝试显式转换为普通向量:

coredata(x$colA)[1] + coredata(x$colB)[2]
## [1] 6

3) c 这里我们将两个值连接到一个新的 xts 对象中,然后将新对象中的值相加。

sum(c(x$colA[1], x$colB[2]))
## [1] 6