[R] Converting ts into xts and subsetting

Gabor Grothendieck ggrothendieck at gmail.com
Thu Feb 16 05:30:29 CET 2012


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.

Any of these work with your sample data:

X2[ trunc(time(X2)) == 1984 ]

X2[ format(time(X2), "%Y") == "1984" ]

window(X2, start = 1984)

window(X, start = 1984)

Sys.setenv(TZ = "GMT")
X2["1984"]


-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list