reshape2 melt date handling

845 views
Skip to first unread message

Alastair

unread,
Apr 28, 2012, 9:21:49 PM4/28/12
to ggp...@googlegroups.com
Hi,

Has anyone encountered a problem using the melt function of reshape2 with date columns? I've melted my data.frame containing two columns of POSIXct dates but the resulting value column has been converted to a numeric rather than retained as a date. Am I using melt incorrectly or have I misunderstood the melting process? Here's a little example that'll reproduce it. 

library(reshape2)
x <- seq(from = as.POSIXlt("2010-01-01", tz = "GMT"), length.out = 20, by = "mins")
y <- seq(from = as.POSIXlt("2010-01-01", tz = "GMT"), length.out = 20, by = "secs")
df <- data.frame(id = 1:20, start = x, end = y) 
melt.df <- melt(df, measure.var = c("start", "end")
class(melt.df$value) # this'll be number rather than POSIXct

Thanks,
Alastair

Dennis Murphy

unread,
Apr 28, 2012, 11:04:04 PM4/28/12
to Alastair, ggp...@googlegroups.com
Yes, the number of seconds since the origin 1970-01-01 00:00:00. Just
redefine value as a POSIXct object from that origin:

melt.df$value <- as.POSIXct(melt.df$value, origin = '1970-01-01 00:00:00')
str(melt.df) # verify that it is indeed POSIXct

If you're wondering why value is returning an integer from melt()
rather than a POSIXct object,

> storage.mode(df$start) # ditto for df$end
[1] "integer"

The POSIXct class stores date/time values as the number of seconds
since January 1, 1970 (at 00:00:00). (Spector 2008, 'Data Manipulation
in R', the last sentence on p. 60 that continues onto the following
page.) I think this is a feature of melt() rather than a bug, but you
could always make a feature request :)

OTOH, if you use the reshape() function in base R, it will return the
values as POSIXct:

dfrshp <- reshape(df, idvar = 'id', varying = c('start', 'end'),
v.names = 'value', direction = 'long')
str(dfrshp)


BTW, questions pertaining to plyr and reshape(2) are more appropriate
for the manipulator listserve; go to http://had.co.nz/reshape/ to
subscribe to that list.

Dennis
>
> Thanks,
> Alastair
>
> --
> You received this message because you are subscribed to the ggplot2 mailing
> list.
> Please provide a reproducible example:
> https://github.com/hadley/devtools/wiki/Reproducibility
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2

Alastair

unread,
Apr 29, 2012, 7:37:46 AM4/29/12
to ggp...@googlegroups.com, Alastair
Thanks for the detailed advice. That's exactly what I needed.

Sorry for cross-posting. I didn't realise there was a dedicated data manipulation list / group. 

Best wishes,
Alastair
Reply all
Reply to author
Forward
0 new messages