gpt4 book ai didi

r - POSIXct 值在 reshape2 dcast 中变为数字

转载 作者:行者123 更新时间:2023-12-04 10:14:49 24 4
gpt4 key购买 nike

我正在尝试使用最新 中的 dcast包 (1.2.1) 对 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

最佳答案

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

关于r - POSIXct 值在 reshape2 dcast 中变为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12289731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com