Saving ts objects as csv files

Hyndsight

Occasionally R might not be the tool you want to use (hard to believe, but apparently that happens). Then you may need to export some data from R via a csv file. When the data is stored as a ts object, the time index can easily get lost. So I wrote a little function to make this easier, using the tsibble package to do almost all of the work in looking after the time index. (Thanks to Earo in the comments for greatly simplifying my original code.)

# Convert time series data to csv
ts2csv <- function(x) {
  fname <- paste0(deparse(substitute(x)), ".csv")
  readr::write_csv(tsibble::as_tsibble(x, gather = FALSE), fname)
}

library(fpp2)
ts2csv(auscafe)    # Univariate monthly data
ts2csv(visnights)  # Multivariate quarterly data
ts2csv(elecdemand) # Multivariate half-hourly data
comments powered by Disqus