【发布时间】:2012-08-30 15:53:56
【问题描述】:
我正在尝试使用最新的 reshape2 包 (1.2.1) 中的 dcast 对 value.var 为 POSIXct 类型的数据帧(或 data.table)进行非规范化,但在生成的数据帧中,日期值已失去其 POSIXct 类并变为数字。
如果我希望将值恢复为 POSIXct 的值,我真的必须 as.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);
运行上述语句的结果(注意新列 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
【问题讨论】:
-
我很困惑。如果您添加新行,因此结果 data.frame 中没有
NA值,则行为仍然存在,但是,相同的acast调用会给出预期的POSIXct结果。