我想使用下面的数据框创建一个xts对象.我理解,因为这是因素和数值组合的组合,它不能在单个xts对象中.我很乐意创建单独的对象,只需按时间进行分组(暂时可以保留日期).
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
}
我知道sapply调用返回POSIXct对象
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"
我的xts对象创建有什么问题吗?
最佳答案 你可以创建你的order.by矢量,而不是:
time <- as.POSIXct(paste(df$date, df$extime), format = "%Y-%m-%d %H:%M:%OS")
然后,创建xts对象:
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
如果要查看小数秒:
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