Reputation: 31
New version of xts seems to have a different behavior when merging xts with different date class indices.
Here is a code example:
library(xts)
x1=xts(1:2,as.Date(c('1990-01-01','1991-01-01')))
x2=xts(3:4,as.POSIXct(c('1990-01-01','1991-01-01')))
merge(x1,x2)
Output using newest version 0.9-5.1 from r-forge:
x1 x2
1990-01-01 1 NA
1990-01-01 NA 3
1991-01-01 2 NA
1991-01-01 NA 4
Same using version 0.8-6 version:
x1 x2
1990-01-01 1 3
1991-01-01 2 4
Is there a way to force xts to convert the index to the same class before merging (as it was before) or the only way to make it work now is to force index class yourself before merging?
It would be great to have object attribute where you could specify what level of time precision you care about while working with it (aka ignore time if you work with daily data etc).
Upvotes: 3
Views: 358
Reputation: 49820
Edit: I'm not sure if the fact that it worked in 0.8-6 was a bug or desired behavior.
This is a timezone issue. Dates are considered to be midnight in UTC, so the index of x1
is in UTC. However, x2
has the timezone of your OS. The index of xts objects is always stored internally as POSIXct which is the number of seconds since the epoch in UTC. If your timezone is not UTC, then when the UTC Date is converted to POSIXct in the timezone of your OS, the times will not match up. One workaround would be to convert the index of one of them to match the other.
> # Convert the POSIXct index to Date
> index(x2) <- as.Date(index(x2))
> merge(x1,x2)
x1 x2
1990-01-01 1 3
1991-01-01 2 4
> x2 <- xts(3:4,as.POSIXct(c('1990-01-01','1991-01-01')))
> # Convert the Date index to POSIXct
> index(x1) <- as.POSIXct(format(index(x1)))
> merge(x1, x2)
x1 x2
1990-01-01 1 3
1991-01-01 2 4
I used format
because as.POSIXct.Date
does not make use of the tz
argument.
In this example, it's possible to work around by setting a TZ
environment variable first. Of course, that may have other implications depending on how you use timezones. And, it only works if you set the timezone variable before creating the xts object.
Sys.setenv(TZ="GMT")
x1=xts(1:2,as.Date(c('1990-01-01','1991-01-01')))
x2=xts(3:4,as.POSIXct(c('1990-01-01','1991-01-01')))
merge(x1, x2)
x1 x2
1990-01-01 1 3
1991-01-01 2 4
Upvotes: 3
Reputation: 18437
Not an answer, just to show OP that there's no problem with the CRAN version (at least for me)
library(xts)
x1=xts(1:2,as.Date(c('1990-01-01','1991-01-01')))
x2=xts(3:4,as.POSIXct(c('1990-01-01','1991-01-01')))
R> merge(x1,x2)
x1 x2
1990-01-01 1 3
1991-01-01 2 4
R> packageVersion("xts")
[1] ‘0.9.5’
Upvotes: 0