出于某种原因,我在创建时间序列对象时遇到问题。示例如下:
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
我会很感激任何指针
答案 0 :(得分: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
答案 1 :(得分:2)
正如@PrasannaNanda回答中所示,您应该创建一个有效的日期时间对象。
strptime
的另一种替代方法是使用lubridate
,这可以让日期,时间和时间跨度变得轻松:
library(lubridate)
xts(dat$V2,Sys.Date()+hms(dat$V1))