pat
pat

Reputation: 627

reshape an index of dates to data frame of dates

I am doing some time series manipulations whereby I reshape some Date vectors into matrix elements for some further processing. But for some reason, I can't seem to re-apply the date class back inside either the matrix or data frame form.

let

idx <- as.Date(seq(20),format="%Y-%m-%d",origin="1970-01-01")
idx.m <- matrix(idx,nrow=5,ncol=4)

gives

  > idx.m
     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20

I convert to a data frame to hold the date objects.

idx.df <- data.frame(idx.m)

If I try some types of applies, I cannot seem to get back the date format.

> apply(idx.df,1,as.Date)
   [,1] [,2] [,3] [,4] [,5]
X1    1    2    3    4    5
X2    6    7    8    9   10
X3   11   12   13   14   15
X4   16   17   18   19   20

Even if the information was lost in the matrix translation, I should still be able to convert back to dates.

I've tried a few other ways, and I could swear I was able to do this in the past. Is there some way to start out with an index vector as above, reshape it, and end up with a dataframe (I don't think a matrix can hold dates, but characters) of dates maintaining the date property?

I could manually build the data frame this way

> idx.a <- idx[1:10]
> idx.b <- idx[11:20]
> data.frame(idx.a,idx.b)
        idx.a      idx.b
1  1970-01-02 1970-01-12
2  1970-01-03 1970-01-13
3  1970-01-04 1970-01-14
4  1970-01-05 1970-01-15
5  1970-01-06 1970-01-16
6  1970-01-07 1970-01-17
7  1970-01-08 1970-01-18
8  1970-01-09 1970-01-19
9  1970-01-10 1970-01-20
10 1970-01-11 1970-01-21
> class(data.frame(idx.a,idx.b))
[1] "data.frame"
> sapply(data.frame(idx.a,idx.b),class)
 idx.a  idx.b 
"Date" "Date" 

Any ideas on what I am missing?

Upvotes: 1

Views: 219

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269634

Try this:

idx <- as.Date(seq(20),format="%Y-%m-%d",origin="1970-01-01")
idx.m <- idx
dim(idx.m) <- c(5, 4)

is.matrix(idx.m)
## TRUE

You can get a cell, e.g. id.m[2, 3], a column, e.g. idx.m[, 2], etc. but not everything will work as expected. print(idx.m) will print it out as if its a vector even though its a matrix and as.data.frame.matrix(idx.m) will convert it to a data frame but strip the "Date" class leaving numbers.

If you do want to convert it to a data frame you will have to work around the limitations:

DF <- as.data.frame.matrix(idx.m)
DF[] <- lapply(DF, as.Date, origin = "1970-01-01")

or

do.call(data.frame, split(idx.m, col(idx.m)))

Upvotes: 4

Related Questions