POSIXct值在reshape2 dcast中变为数字

gka*_*pas 6 r reshape2

我正在尝试使用最新的包(1.2.1)中的来对数据帧(或data.table)进行非规范化,其中value.var是POSIXct类型,但在结果数据框中,日期值已丢失他们的POSIXct类并成为数字.

我是否真的必须as.POSIXct()每个生成的列,如果我想将值恢复为POSIXct的,或者我错过了什么?

x <- c("a","b");
y <- c("c","d");
z <- as.POSIXct(c("2012-01-01 01:01:01","2012-02-02 02:02:02"));
d <- data.frame(x, y, z, stringsAsFactors=FALSE);
str(d);
library(reshape2);
e <- dcast(d, formula = x ~ y, value.var = "z");
str(e);
Run Code Online (Sandbox Code Playgroud)

运行上述语句的结果(注意新列c和d是数字纪元秒而不是POSIXct):

> x <- c("a","b");
> y <- c("c","d");
> z <- as.POSIXct(c("2012-01-01 01:01:01","2012-02-02 02:02:02"));
> d <- data.frame(x, y, z, stringsAsFactors=FALSE);
> str(d);
'data.frame':   2 obs. of  3 variables:
 $ x: chr  "a" "b"
 $ y: chr  "c" "d"
 $ z: POSIXct, format: "2012-01-01 01:01:01" "2012-02-02 02:02:02"
> library(reshape2);
> e <- dcast(d, formula = x ~ y, value.var = "z");
> str(e);
'data.frame':   2 obs. of  3 variables:
 $ x: chr  "a" "b"
 $ c: num  1.33e+09 NA
 $ d: num  NA 1.33e+09
Run Code Online (Sandbox Code Playgroud)

Jos*_*ien 9

这样做debug(dcast)debug(as.data.frame.matrix),然后通过你的推出计算步进dcast()通话将显示,在这些线路as.data.frame.matrix()有过错:

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])
}
Run Code Online (Sandbox Code Playgroud)

当前的POSIXct对象具有模式"numeric",因此评估遵循第二个分支,该分支将结果转换为数字.

如果你使用dcast(),看起来你需要后处理结果,如果你有正确的,这应该不会太难origin.像这样的东西(它没有完全origin正确)应该做的伎俩:

e[-1] <- lapply(e[-1], as.POSIXct, origin="1960-01-01")
Run Code Online (Sandbox Code Playgroud)

FWIW,base R reshape()将保留POSIXct值,但需要您编辑结果列的名称......

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
Run Code Online (Sandbox Code Playgroud)