Question

I am subtracting dates in xts i.e.

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))
  • Question: How can I standardise the result so that I always get the answer in hours. Not by multiplying the days by 24 as I will not know before han whther the subtratcion will round to days or hours.... Unless I can somehow check if the format is in days perhaps using grep and regexand then multiply within an if clause.

I have tried to work through this and went for the grep regex apprach but this doesnt even keep the negative sign..

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 

I am convinced there is a more elegant solution...

Was it helpful?

Solution

ok difftime works...

 transform(xxts, lag = difftime(as.POSIXct(BDate, format = "%d/%m/%Y %H:%M"), index(xxts), unit = "hours"))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top