joshuaulrich / xts

Extensible time series class that provides uniform handling of many R time series classes by extending zoo.
http://joshuaulrich.github.io/xts/
GNU General Public License v2.0
219 stars 71 forks source link

double square brackets in xts objects #125

Open fcasarramona opened 9 years ago

fcasarramona commented 9 years ago

While is posible to select one single element of a xts object with single square brakets:

library(xts)
data(sample_matrix)
sample.xts <- as.xts(sample_matrix, descr='my new xts object')
sample.xts["2007-06-28", 1]
           Open
2007-06-28 47.67604

returning a xts object, selecting with double square brackets returns an error:

sample.xts[["2007-06-28", 1]]
Error in sample.xts[["2007-06-28", 1]] : subscript out of bounds

but I expect returning a numeric.

Workarrounds are:

as.numeric(sample.xts["2007-06-28", 1])

or, type independent:

drop(coredata(sample.xts["2007-06-28", 1]))
joshuaulrich commented 9 years ago

To clarify, this works with matrix and zoo objects because [[ with character i matches on rownames (technically, dimnames(x)[[1]]), but xts objects do not have rownames.

> sample_matrix[["2007-06-28",1]]
[1] 47.67604
> as.zoo(sample_matrix)[["2007-06-28",1]]
[1] 47.67604
> as.xts(sample_matrix)[["2007-06-28",1]]
Error in as.xts(sample_matrix)[["2007-06-28", 1]] : 
  subscript out of bounds

I think the solution would be to create a [[.xts method.