2014-07-15 30 views
3

我想使用下面的數據框創建xts對象。我明白,因爲這是因素和數值組合的組合,因此它不能位於單個xts對象中。我很樂意創建分組對象,只需按時間完成分組(現在可以保留日期)。R使用時間字符串創建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對象的創建?

+0

的'sapply'調用*不會*返回'POSIXct'對象。它返回一個* POSIXct對象的*列表。 –

回答

1

您可以創建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