2
votes

I want to subset a range of quarterly data held inside an xts object.

I see the documentation says "xts provides facilities for indexing based on any of the current time-based classes. These include yearqtr"

However I have tried the following, which do produce a range of data but not the dates I request.

a = as.xts(ts(rnorm(20), start=c(1980,1), freq=4))
a["1983"] # Returns 1983Q2 - 1984Q1 ?
a["1983-01/"] # Begins in 1983Q2 ?
a["1981-01/1983-03"] # Returns 1981Q2 - 1983Q2 ?

a[as.yearqtr("1981 Q2")] # Correct
a[as.yearqtr("1981 Q1")/as.yearqtr("1983 Q3")] # Does not work
1

1 Answers

0
votes

Looks like a timezone issue. The xts index is always a POSIXct object, even if the index class is something else. Like a Date classed index, the yearqtr (and yearmon) classed index should have the timezone set to "UTC".

> a <- as.xts(ts(rnorm(20), start=c(1980,1), freq=4), tzone="UTC")
> a["1983"]
              [,1]
1983 Q1  1.4877302
1983 Q2 -0.4594768
1983 Q3 -0.1906189
1983 Q4 -1.1518943
Warning message:
timezone of object (UTC) is different than current timezone (). 

You can safely ignore the warning. If it really bothers you, you can set your R session's timezone to "UTC" via:

> Sys.setenv(TZ="UTC")
> a <- as.xts(ts(rnorm(20), start=c(1980,1), freq=4))
> a["1983"]
               [,1]
1983 Q2  1.84636890
1983 Q3 -0.06872544
1983 Q4 -2.29822631
1984 Q1 -1.46025131

This will never work:

a[as.yearqtr("1981 Q1")/as.yearqtr("1983 Q3")] # Does not work

It looks like you're trying to do something like: a["1981 Q1/1983 Q3"], which isn't supported because "YYYY Qq" is not an ISO8601 format.