[R-SIG-Finance] Writing code that works with a variety of time series classes

Achim Zeileis Achim.Zeileis at wu-wien.ac.at
Sat Oct 4 20:31:40 CEST 2008


On Sat, 4 Oct 2008, Ajay Shah wrote:

> I'm writing a function where I want to support two cases:
>    - caller supplies a pure numeric
> or
>    - caller supplies a time series object
>
> For the latter case, R now has a variety of time series classes : ts,
> zoo, its, xts, etc. I only require two operations:
>
>     I want to pull out the datetime stamps (e.g. index(a.zoo))

index() is a "zoo-ism" because the index does not need to correspond to 
"time". But time() is perfectly ok and a bit more expressive in time 
series applications.

>     I want to then convert down to a numeric (e.g. as.numeric(a.zoo))

as.numeric() only does the right thing if you have a univariate series. 
coredata() is recommended and will return either a vector or a matrix.

> Between all the people building time series classes, is there an
> agreement on some minimal set of functions that will always be
> supported?

Not much, time() usually works but the functions for extracting the data 
vary somewhat.

> Do index(z) and as.numeric(z) work consistently across all
> the time series classes? And, I think we need a function is.tsclass()
> which reports TRUE if the object supplied is a zoo, its, ts or xts.

I would argue that you can always coerce to zoo first
   as.zoo(some_object)
which works for the classes above and some more like timeSeries. Then you 
can compute with a unified object and, if necessary, coerce some output 
series back to the original class. In addition, you could leverage 
xts's unification of time-based indexes.
Z



More information about the R-SIG-Finance mailing list