用标准化结果减去日期

时间:2014-02-12 11:15:16

标签: r date xts posixct

我在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,因为我不知道之前的情况是否会在几天或几小时内完成.... 除非我能够以某种方式检查格式是否在几天内使用grepregex然后在if子句中相乘。

我试图解决这个问题,然后去了grep regex apprach,但这甚至没有留下负号......

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 

我确信有更优雅的解决方案......

1 个答案:

答案 0 :(得分:0)

确定difftime有效......

 transform(xxts, lag = difftime(as.POSIXct(BDate, format = "%d/%m/%Y %H:%M"), index(xxts), unit = "hours"))