POSIXct values become numeric in reshape2 dcast

匆匆过客 提交于 2019-12-05 08:13:34

Doing debug(dcast) and debug(as.data.frame.matrix), then stepping through the calculations launched by your dcast() call will reveal that these lines in as.data.frame.matrix() are at fault:

if (mode(x) == "character" && stringsAsFactors) {
    for (i in ic) value[[i]] <- as.factor(x[, i])
}
else {
    for (i in ic) value[[i]] <- as.vector(x[, i])
}

The up-to-then POSIXct object has mode "numeric", so evaluation follows the second branch, which converts the results to numeric.

If you use dcast(), it looks like you will need to post-process results, which shouldn't be too hard if you have the correct origin. Something like this (which doesn't quite get the origin right) should do the trick:

e[-1] <- lapply(e[-1], as.POSIXct, origin="1960-01-01")

FWIW, base R's reshape() leaves POSIXct values as they are but will require you to edit the names of the resulting columns...

reshape(d, idvar="x", timevar="y",  direction="wide")
#   x                 z.c                 z.d
# 1 a 2012-01-01 01:01:01                <NA>
# 2 b                <NA> 2012-02-02 02:02:02

I just encountered this problem as well. I solved it by first coercing the date field into character, then dcast, and then converting back into a date.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!