Exercise

Converting xts objects

It is often necessary to convert between classes when working with time series data in R. Conversion can be required for many reasons, but typically you'll be looking to use a function that may not be time series aware or you may want to use a particular aspect of xts with something that doesn't necessarily need to be a full time series.

Luckily, it is quite easy to convert back and forth using the standard as.* style functionality provided in R (for example, as.POSIXct() or as.matrix()).

xts provides methods to convert all of the major objects you are likely to come across. Suitable native R types like matrix, data.frame, and ts are supported, as well as contributed ones such as timeSeries, fts and of course zoo. as.xts() is the workhorse function to do the conversions to xts, and similar functions will provide the reverse behavior.

To get a feel for moving data between classes, let's try a few examples using the Australian population ts object from R named austres.

Instructions

100 XP
  • Convert the ts class austres data set to an xts and call it au.
  • Then convert the new au xts object into a matrix, am.
  • Inspect the first few entries of this new matrix by using the head() function.
  • Convert the original austres directly into a matrix called am2.
  • Now inspect the first few entries of this new matrix by using the same function. Notice how this time, the conversion didn't preserve the time information?