Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 most of the work in looking after the time index.

# Convert time series data to csv
ts2csv <- function(x) {
fname <- paste0(deparse(substitute(x)), ".csv")
if (NCOL(x) == 1L) {
# Univariate time series
as.data.frame(tsibble::as_tsibble(x)),
fname)
} else {
# Multivariate time series
fname)
}
}

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