POSIXct值在reshape2 dcast中变成了数字型。

问题描述 投票:6回答:3

我正试图使用最新版本的dcast。 包(1.2.1)来对一个数据框(或data.table)进行去规范化,其中value.var是POSIXct类型,但在生成的数据框中,日期值失去了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
r reshape2
3个回答
10
投票

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])
}

POSIXct对象的模式为 "numeric"因此,评估是在第二个分支之后进行的,它将结果转换为数字。

如果你使用 dcast()貌似你需要对结果进行后处理,这应该不难。如果 你有正确 origin. 类似于这样的东西(它并没有完全得到的是 origin 右)应该可以做到这一点。

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

FWIW,基础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

0
投票

我刚刚也遇到了这个问题。我是通过先将日期字段胁迫成字符,然后dcast,再转换回日期来解决的。


0
投票

当castwidening一个数据集时,对日期完整性的预处理和或后处理是非常麻烦的。

在这方面,除非你需要的重塑很复杂。pivot_wider() 从包 潮人 是尊重dates对象的--途中没有转换。此外,它给了铸造过程更多的控制权,从而避免了后处理步骤 (https:/tidyr.tidyverse.orgreferencepivot_wider.html。).

© www.soinside.com 2019 - 2024. All rights reserved.