Question

For some reason I am having issues creating a time series object. Example below:

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

By using the same approach I normally use:

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

I would appreciate any pointers

Was it helpful?

Solution

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

OTHER TIPS

As already shown in @PrasannaNanda answer, you should create a valid datetime object.

Another alternative to strptime, is to use lubridate which make life easy with dates, times and time spans:

library(lubridate)
xts(dat$V2,Sys.Date()+hms(dat$V1))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top