Florent Florent - 1 month ago 11
R Question

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

I would like to subset dates from an xts objet based on logical values in another xts object, but RStudio returns an out-of-range error despite in-range values.

For example I would like to filter dates and prices where RSI is above 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


This is not the output I expect because both my objects have data until the 2016-10-21. What could be wrong ? I would like something like :

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


This is the
str
of my xts objects :

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


Thank you,

Answer

You didn't make a reproducible example, so here is some toy data. Your issue is that you did not subset strength with the same time window (so your inner strength == TRUE logical series has different row length to your d row length, generating your error. i.e. NROW(strength == TRUE) >> NROW(d["2016-10-17::"]) ):

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

You shouldn't get an error if you do this:

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