Converting an xts object to a data frame in R

I feel like the last few days I’ve been struggling with what I would consider novice problems in R.

Today I spent a few minutes trying to remember how to convert an xts object to a data frame while preserving the time stamp as a column that can be accessed. I just stumbled across this post from Jeffrey Breen which shows you how to do just that as well as overlay recession bars on top of a timeseries plot (ANOTHER thing I spent a few hours on recently, UGH!).

Anyway, the relevant codes is pretty straightforward. Simply use the time() and coredata() functions to cast your timeseries elements into vectors and then stuff them into your data frame. The code below assumes you want to convert an xts object of the VIX volatility index returns.

ticker <- "^VIX" ## VIX index
 
getSymbols(ticker)
 
chartSeries(VIX)
 
vix.returns <- allReturns(VIX)
vix.returns.df <- data.frame(date=time(vix.returns),coredata(vix.returns$daily))

Created by Pretty R at inside-R.org