[英]difftime in R is not calculating correctly
我试图找出两个日期之间的时差,以小时为单位,而对于超过一天的时间间隔中出现的时差,我得到的数字实在令人难以置信和错误。
这是数据示例:
Observation Status DateTime
1 Active 2016-11-04 22:32:49
2 Inactive 2016-11-05 08:30:56
我正在运行以下命令:
getDiff <- function(x) {
difftime(shift(x, fill = NA, type = "lead"), x, units = "hours")
}
diff_result <- dataframe[, time.diff := ifelse(Status == "Active",
getDiff(DateTime), NA)]
我得到以下输出:
Observation Status DateTime Time.diff
1 Active 2016-11-04 22:32:49 8757.884
2 Inactive 2016-11-05 08:30:56
此命令适用于所有其他在不同日期不会发生的差异。 正确答案应该在10小时左右,而不是超过8000。
也,
> class(DataFrame$DateTime)
[1] "POSIXct" "POSIXt"
先感谢您!
看来OP没有正确转换DateTime
格式。 8757
小时相当于大约1年。 因此,很有可能DateTime
格式错误。
最后,使用OP的数据,结果看起来不错。
library(data.table)
getDiff <- function(x) {
difftime(shift(x, fill = NA, type = "lead"), x, units = "hours")
}
setDT(df)
diff_result <- df[, time.diff := ifelse(Status == "Active",
getDiff(DateTime), NA)]
diff_result
# Observation Status DateTime time.diff
# 1: 1 Active 2016-11-04 22:32:49 9.968611
# 2: 2 Inactive 2016-11-05 08:30:56 NA
#
数据:
df <- read.table(text =
"Observation Status DateTime
1 Active '2016-11-04 22:32:49'
2 Inactive '2016-11-05 08:30:56'",
header = TRUE, stringsAsFactors = FALSE)
df$DateTime = as.POSIXct(df$DateTime, format = "%Y-%m-%d %H:%M:%S")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.