【发布时间】:2014-03-10 16:28:30
【问题描述】:
我正在减去xts 中的日期,即
library(xts)
# make data
x <- data.frame(x = 1:4,
BDate = c("1/1/2000 12:00","2/1/2000 12:00","3/1/2000 12:00","4/1/2000 12:00"),
CDate = c("2/1/2000 12:00","3/1/2000 12:00","4/1/2000 12:00","9/1/2000 12:00"),
ADate = c("3/1/2000","4/1/2000","5/1/2000","10/1/2000"),
stringsAsFactors = FALSE)
x$ADate <- as.POSIXct(x$ADate, format = "%d/%m/%Y")
# object we will use
xxts <- xts(x[, 1:3], order.by= x[, 4] )
#### The subtractions
# anwser in days
transform(xxts, lag = as.POSIXct(BDate, format = "%d/%m/%Y %H:%M") - index(xxts))
# asnwer in hours
transform(xxts, lag = as.POSIXct(CDate, format = "%d/%m/%Y %H:%M") - index(xxts))
- 问题:如何标准化结果,以便始终在数小时内得到答案。 不是将天数乘以 24,因为我不知道减法会舍入到天还是小时......
除非我可以使用
grep和regex以某种方式检查格式是否以天为单位,然后在if子句中相乘。
我已经尝试解决这个问题并选择了grep regex 方法,但这甚至没有保留负号..
p <- transform(xxts, lag = as.POSIXct(BDate, format = "%d/%m/%Y %H:%M") - index(xxts))
library(stringr)
ind <- grep("days", p$lag)
p$lag[ind] <- as.numeric( str_extract_all(p$lag[ind], "\\(?[0-9,.]+\\)?")) * 24
p$lag
#2000-01-03 2000-01-04 2000-01-05 2000-01-10
# 36 36 36 132
我相信有一个更优雅的解决方案...
【问题讨论】:
-
考虑将 R 作为标签添加到您的问题中
-
哎呀错过了那个标签,谢谢@Vincent