Reputation: 41
I want to create an xts
object using the below data frame. I understand since this is a combination of factors and combination of numeric values it cannot be in a single xts
object. I am happy to create seperate objects with grouping done just by time (ok to leave date for the moment).
date extime sym price size notional ex
1 2014-06-30 08:00:05.330 RRS.L 4895 2 9790 XLON
2 2014-06-30 08:00:09.101 RRS.L 4893 23 112539 XLON
3 2014-06-30 08:00:10.257 RRS.L 4893 119 582267 XLON
4 2014-06-30 08:00:12.575 RRS.L 4892 128 626176 XLON
xts(testData$price, sapply(testData$extime, function(df) as.POSIXct((getNumericTim(df) +0.1)/1000, origin = "2014-06-30"),simplify=FALSE))
# Error in xts(testData$price, sapply(testData$extime, function(df) as.POSIXct((getNumericTime(df) + :
# order.by requires an appropriate time-based object
getNumericTime
function (x){
options(digits.secs=3)
data <- strptime(x,format="%H:%M:%OS")
hr <- as.numeric(strftime(data,"%H"))
mins <- as.numeric(strftime(data,"%M"))
secs <- as.numeric(strftime(data,"%OS"))
(((hr*(60)+mins)*60)+secs)*1000
}
I know the sapply
call returns POSIXct
object
sapply(testData$extime,function(df)as.POSIXct((getNumericTime(df)+0.1)/1000, origin = "2014-06-30"),simplify=FALSE)
[[1]]
[1] "2014-06-30 09:00:05.330 BST"
[[2]]
[1] "2014-06-30 09:00:09.101 BST"
[[3]]
[1] "2014-06-30 09:00:10.257 BST"
[[4]]
[1] "2014-06-30 09:00:12.575 BST"
Anything wrong with my xts
object creation ?
Upvotes: 4
Views: 9500
Reputation: 67818
You may create your order.by
vector like this instead:
time <- as.POSIXct(paste(df$date, df$extime), format = "%Y-%m-%d %H:%M:%OS")
Then, create xts
object:
library(xts)
xt <- xts(x = df$price, order.by = time)
xt
# [,1]
# 2014-06-30 08:00:05 4895
# 2014-06-30 08:00:09 4893
# 2014-06-30 08:00:10 4893
# 2014-06-30 08:00:12 4892
If you want to view the fractional seconds:
options(digits.secs = 3)
xt
# [,1]
# 2014-06-30 08:00:05.329 4895
# 2014-06-30 08:00:09.101 4893
# 2014-06-30 08:00:10.256 4893
# 2014-06-30 08:00:12.575 4892
Upvotes: 2