对 R 中的 xts 对象的值进行子集化时出现超出范围错误

out-of-range error when subseting values from an xts object in R

我想根据另一个 xts 对象中的逻辑值从一个 xts 对象中提取日期子集,但是 R returns 尽管具有范围内的值,但仍出现超出范围的错误。

例如,我想过滤 RSI 高于 60 的日期和价格。

> strength <- RSI(d, 14)>60
> strength["2016-10-17::"]
             RSI
2016-10-17  TRUE
2016-10-18  TRUE
2016-10-19  TRUE
2016-10-20 FALSE
2016-10-21 FALSE

> d["2016-10-17::"]
               Open
2016-10-17 642.2760
2016-10-18 640.5988
2016-10-19 637.0000
2016-10-20 631.9800
2016-10-21 633.6470

> d["2016-10-17::"][strength == TRUE]
Error in `[.xts`(d["2016-10-17::"], strength == TRUE) : 
  'i' or 'j' out of range

这不是我期望的输出,因为我的两个对象在 2016 年 10 月 21 日之前都有数据。有什么问题吗?我想要类似的东西:

> d["2016-10-17::"][strength == TRUE]
               Open
2016-10-17 642.2760
2016-10-18 640.5988
2016-10-19 637.0000

这是我的 xts 对象的 str

> str(d)
An ‘xts’ object on 2013-09-02/2016-10-21 containing:
  Data: num [1:1146, 1] 127 128 121 121 116 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr "Open"
  Indexed by objects of class: [Date] TZ: UTC
  xts Attributes:  
List of 2
 $ dateFormat: chr "Date"
 $ na.action :Class 'omit'  atomic [1:92] 1 2 3 4 5 6 7 8 9 10 ...
  .. ..- attr(*, "index")= num [1:92] 1.37e+09 1.37e+09 1.37e+09 1.37e+09 1.37e+09 ...

> str(strength)
An ‘xts’ object on 2013-09-16/2016-10-21 containing:
  Data: logi [1:1132, 1] FALSE FALSE FALSE FALSE FALSE FALSE ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr "RSI"
  Indexed by objects of class: [Date] TZ: UTC
  xts Attributes:  
 NULL
> 

谢谢

您没有制作可重现的示例,所以这里有一些玩具数据。你的问题是你没有同时 window 子集强度(所以你的内部 strength == TRUE 逻辑序列的行长度与你的 d 行长度不同,产生你的错误。即 NROW(strength == TRUE) >> NROW(d["2016-10-17::"]) ):

library(quantmod)
getSymbols("AAPL")
d <- AAPL
strength <- RSI(Cl(d)) > 60

如果你这样做,你不应该得到一个错误:

d["2016-10-17::"][strength["2016-10-17::"] == TRUE]