(This article was first published on

**R on Rob J Hyndman**, and kindly contributed to R-bloggers)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
readr::write_csv(
as.data.frame(tsibble::as_tsibble(x)),
fname)
} else {
# Multivariate time series
readr::write_csv(
as.data.frame(tsibble::spread(tsibble::as_tsibble(x), key, value)),
fname)
}
}
library(fpp2)
ts2csv(auscafe) # Univariate monthly data
ts2csv(visnights) # Multivariate quarterly data
ts2csv(elecdemand) # Multivariate half-hourly data
```

To

**leave a comment**for the author, please follow the link and comment on their blog:**R on Rob J Hyndman**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...