[R-SIG-Finance] xts: Is this the expected behaviour?

Joshua Ulrich josh.m.ulrich at gmail.com
Mon Dec 23 23:57:38 CET 2013


On Mon, Dec 23, 2013 at 4:07 PM, Ivan Popivanov
<ivan.popivanov at gmail.com> wrote:
> Best to jump straight to code:
>
> xx = xts(1:10, as.Date("2000-01-01")+1:10)
> xx[c("2000-01-04", "2000-01-03", "2000-01-03"), which.i=T]
> [1] 2 2 3
> xx[as.Date(c("2000-01-04", "2000-01-03", "2000-01-03")), which.i=T]
> [1] 2 3
>
> Btw ... hi :)
>
> Is this working as designed? And second, is it possible to get the integer
> indexes, with repetitions preserved, without ordering them? In other words,
> how to get 3 2 2 without looping and independent of the type of the index?
>
Duplicated index values are not formally supported in zoo (see ?zoo),
so you shouldn't expect them to be completely well-behaved in xts
either.

Generally, you shouldn't expect zoo/xts functions to yield unordered
results.  They are classes for ordered data, after all.  That said,
here's one way to do what you want:

# create a 1-column xts object, where the value is the row number
X <- xts(1:nrow(xx),index(xx))
# create another 1-column xts object with the index values
# you want to extract, and their row numbers
d <- as.Date(c("2000-01-04", "2000-01-03", "2000-01-03"))
D <- xts(1:length(d),d)
# merge them, only keeping the index values from D
# and filling in the NA created in X
M <- merge(X,D,join="right",fill=na.locf)
# now you can convert M to a data.frame
m <- data.frame(M)
# and order column X by column D
m$X[order(m$D)]

> Thanks in advance, and Merry Christmas!
> Ivan
>
Merry Christmas to you too.

Best,
--
Joshua Ulrich  |  about.me/joshuaulrich
FOSS Trading  |  www.fosstrading.com



More information about the R-SIG-Finance mailing list