2014-01-30 128 views
1

由於某些原因,我在創建時間序列對象時遇到了問題。下面的例子:無法創建文本文件

dat = read.csv("latency.csv", header = FALSE) 
x <- dat[1:10,1:2] 
x 
     V1  V2 
1 08:48:17 85.258 
2 08:48:17 39.471 
3 09:00:02 11.645 
4 09:00:02 39.380 
5 09:00:02 40.866 
6 09:00:17 22.138 
7 09:00:21 10.935 
8 09:00:30 40.884 
9 09:00:30 41.130 
10 09:00:30 40.230 

通過使用相同的方法,我通常使用:

my.xts <- xts(dat[,-1], order.by=dat[,1]) 
Error in xts(dat[, -1], order.by = dat[, 1]) : 
    order.by requires an appropriate time-based object 

我將不勝感激任何指針

+1

錯誤消息是相當有價值的信息。您需要將您的'order.by'變量轉換爲其中一個「可接受的類」。從'?xts':「...必須是基於時間的類。目前可接受的類包括:'Date','POSIXct','timeDate'以及'yearmon'和'yearqtr',其中索引值保持獨特「。檢查'str(dat)'。 – Henrik

回答

5
dat <- read.table(textConnection("V1  V2 
1 08:48:17 85.258 
2 08:48:17 39.471 
3 09:00:02 11.645 
4 09:00:02 39.380 
5 09:00:02 40.866 
6 09:00:17 22.138 
7 09:00:21 10.935 
8 09:00:30 40.884 
9 09:00:30 41.130 
10 09:00:30 40.230"), header =TRUE) 

str(dat) 

'data.frame': 10 obs. of 2 variables: 
$ V1: Factor w/ 5 levels "08:48:17","09:00:02",..: 1 1 2 2 2 3 4 5 5 5 
$ V2: num 85.3 39.5 11.6 39.4 40.9 ... 


as.character(dat$V1) 

[1] "08:48:17" "08:48:17" "09:00:02" "09:00:02" "09:00:02" "09:00:17" "09:00:21" "09:00:30" "09:00:30" 
[10] "09:00:30" 

strptime(as.character(dat$V1),'%H:%M:%OS') 

[1] "2014-01-30 08:48:17" "2014-01-30 08:48:17" "2014-01-30 09:00:02" "2014-01-30 09:00:02" 
[5] "2014-01-30 09:00:02" "2014-01-30 09:00:17" "2014-01-30 09:00:21" "2014-01-30 09:00:30" 
[9] "2014-01-30 09:00:30" "2014-01-30 09:00:30" 

as.POSIXct(strptime(as.character(dat$V1),'%H:%M:%OS')) 

[1] "2014-01-30 08:48:17 IST" "2014-01-30 08:48:17 IST" "2014-01-30 09:00:02 IST" 
[4] "2014-01-30 09:00:02 IST" "2014-01-30 09:00:02 IST" "2014-01-30 09:00:17 IST" 
[7] "2014-01-30 09:00:21 IST" "2014-01-30 09:00:30 IST" "2014-01-30 09:00:30 IST" 
[10] "2014-01-30 09:00:30 IST" 

x <- xts(dat[-1], 
      order.by=as.POSIXct(strptime(as.character(dat$V1), 
             '%H:%M:%OS'))) 
x 
         V2 
2014-01-30 08:48:17 85.258 
2014-01-30 08:48:17 39.471 
2014-01-30 09:00:02 11.645 
2014-01-30 09:00:02 39.380 
2014-01-30 09:00:02 40.866 
2014-01-30 09:00:17 22.138 
2014-01-30 09:00:21 10.935 
2014-01-30 09:00:30 40.884 
2014-01-30 09:00:30 41.130 
2014-01-30 09:00:30 40.230 
+0

非常感謝,看着數據,我確信它已經以正確的格式,謝謝你的推動。 –

2

正如已經在@PrasannaNanda答案所示,您應該創建一個有效的日期時間對象。

另一種替代strptime,是使用lubridate這也使生活容易日期,時間和時間跨度:

library(lubridate) 
xts(dat$V2,Sys.Date()+hms(dat$V1))