# Saving ts objects as csv files

[This article was first published on

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

**R on Rob J Hyndman**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)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 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 about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

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