[R] Converting ts into xts and subsetting

R. Michael Weylandt michael.weylandt at gmail.com
Thu Feb 16 04:40:50 CET 2012


Time zones strike again!

In short, your problem is that your machine is probably not in UTC for
its timezone (and it probably shouldn't be) so 12:00am Jan1 in London
is still Dec31 for you. To see this directly, look at
as.POSIXct(time(X2)) -- you'll see that item 97 which "should be" Jan
1 is actually late in the day on Dec 31. Compare this to time(X2) and
you'll get a nasty surprise.

The right course of action is a little tricky: where is your data
coming from? Is there a time zone associated with it and, if so, is it
the same one your machine has?

You can set the TZ of a xts object, but the kludgy (read: easier) way
to do it might be to just add the offset to the time object: something
like time(X2) <- time(X2) + 6*60*60. If you are doing monthly
frequency stuff, this hopefully won't hurt anything but I make no
promises.

But if you can say more about the data source and your intended use,
I'd be happy to give more particular thoughts.

Hope this helps,

Michael

On Wed, Feb 15, 2012 at 10:25 PM, P.B. Lecavalier <p.barill at gmail.com> wrote:
> Greetings,
>
> I would like to subset observations in a time series using xts, after
> converting from ts to xts.
>
> X=ts(1:100, frequency=12, start=c(1976))
> X2=as.xts(X)
> X2["1984"]
>
> The output:
>
> Feb 1984   98
> Mar 1984   99
> Apr 1984  100
>
> What happened to January? The index is always one month off, with
> X2["1976-01"] giving me Feb 1976. Should I set the time using something else
> than ts?
>
> I know there is the window function, but the xts format is convenient for my
> needs.
>
> Thank you.
>
> --
> Philippe Baril Lecavalier
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list