2014-02-12 76 views
1

減去日期我減去日期在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天乘以因爲我不會韓之前知道whther的subtratcion將舍入到幾天甚至幾個小時.... 除非我能以某種方式檢查,如果格式是天也許使用grepregex,然後不if子句內相乘。

我試圖通過這個工作,去爲grepregex 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 

我相信還有一個更優雅的解決方案...

+0

考慮增加R作爲標記您的問題 – Vincent

+0

哎呀錯過了標籤,謝謝@Vincent – user1320502

回答

0

確定difftime作品...

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