30
votes

I want to transform my ts object to data.frame object. My MWE is given below:

Code

set.seed(12345)
dat <- ts(data=runif(n=10, min=50, max=100), frequency = 4, start = c(1959, 2))
library(reshape2)
df <- data.frame(date=as.Date(index(dat)), Y = melt(dat)$value)

Output

         date        Y
1  1975-05-14 86.04519
2  1975-05-14 93.78866
3  1975-05-14 88.04912
4  1975-05-15 94.30623
5  1975-05-15 72.82405
6  1975-05-15 58.31859
7  1975-05-15 66.25477
8  1975-05-16 75.46122
9  1975-05-16 86.38526
10 1975-05-16 99.48685

I have lost my quarters in date columns. How can I figure out the problem?

4

4 Answers

39
votes

How about

data.frame(Y=as.matrix(dat), date=time(dat))

This returns

          Y    date
1  86.04519 1959.25
2  93.78866 1959.50
3  88.04912 1959.75
4  94.30623 1960.00
5  72.82405 1960.25
6  58.31859 1960.50
7  66.25477 1960.75
8  75.46122 1961.00
9  86.38526 1961.25
10 99.48685 1961.50
15
votes

yearmon (from zoo) allows creating Date objects.

> dat <- ts(data=runif(n=10, min=50, max=100), frequency = 4, start = c(1959, 2))
> data.frame(Y=as.matrix(dat), date=as.Date(as.yearmon(time(dat))))
          Y       date
1  51.72677 1959-04-01
2  57.61867 1959-07-01
3  86.78425 1959-10-01
4  50.05683 1960-01-01
5  69.56017 1960-04-01
6  73.12473 1960-07-01
7  69.40720 1960-10-01
8  70.12426 1961-01-01
9  58.94818 1961-04-01
10 97.58294 1961-07-01
9
votes

The package timetk has several conversion functions. In your case:

dat <- ts(data=runif(n=10, min=50, max=100), frequency = 4, start = c(1959, 2))

timetk::tk_tbl(dat)

    # A tibble: 10 x 2
           index    value
   <S3: yearqtr>    <dbl>
 1       1959 Q2 86.04519
 2       1959 Q3 93.78866
 3       1959 Q4 88.04912
 4       1960 Q1 94.30623
 5       1960 Q2 72.82405
 6       1960 Q3 58.31859
 7       1960 Q4 66.25477
 8       1961 Q1 75.46122
 9       1961 Q2 86.38526
10       1961 Q3 99.48685
4
votes

Seems that converting from xts objects seems to be both reliable and well documented. Below works and with the new date column in date / yearqtr class.

library(xts)
datx <- as.xts(dat)
df   <- data.frame(date=index(datx), coredata(datx))

Checking class of date:

class(df$date)
[1] "yearqtr"

And result:

print(df)

  date coredata.datx.
1  1959 Q2       86.04519
2  1959 Q3       93.78866
3  1959 Q4       88.04912
4  1960 Q1       94.30623
5  1960 Q2       72.82405
6  1960 Q3       58.31859
7  1960 Q4       66.25477
8  1961 Q1       75.46122
9  1961 Q2       86.38526
10 1961 Q3       99.48685