Joachim Schork
Joachim Schork

Reputation: 2147

Convert ts object to data.frame and keep row- and colnames

I want to convert a ts (i.e. timeseries) R object to a data.frame. The names of rows and columns of the ts object should be retained.

Consider the AirPassengers data set:

data(AirPassengers)

I could convert this ts object to a data.frame as follows:

AirPassengers <- data.frame(matrix(as.numeric(AirPassengers), ncol = 12, byrow = TRUE))
colnames(AirPassengers) <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
rownames(AirPassengers) <- 1949:1960

However, this seems to be way too complicated. Surprisingly, a google search didn't show a simpler solution.

Question: Is there a simple solution how to convert ts objects to a data.frame without losing colnames and rownames?

Upvotes: 3

Views: 969

Answers (1)

Jozef
Jozef

Reputation: 2747

The underlying issue is that the output of print for a time series object is quite heavily processed by .preformat.ts. If you want to convert it to a data frame that is visually similar to the print results this should do:

df <- data.frame(.preformat.ts(datasets::AirPassengers), stringsAsFactors = FALSE)

Note that this will produce characters (as that is how .preformat.ts works), so be careful with the use (not sure what is the purpose of the conversion?).

Upvotes: 4

Related Questions