尝试在xts中使索引唯一时出现问题

时间:2013-05-13 21:45:56

标签: r xts

我有以下xts对象:

options("digits.secs" = 1)
ex <- structure(c(NA, -63L, NA, NA, NA, NA, NA, 0L, NA, NA, NA, NA, 
NA, 1L, NA, NA, NA, NA), .Dim = c(6L, 3L), .Dimnames = list(NULL, 
    c("V2", "V3", "V4")), index = structure(c(1366088402.46, 
1366088402.46, 1366088402.463, 1366088402.463, 1366088469.697, 
1366088469.697), tzone = "", tclass = c("POSIXct", "POSIXt")),
class = c("xts", "zoo"), .indexCLASS = c("POSIXct", "POSIXt"),
tclass = c("POSIXct", "POSIXt"), .indexTZ = "", tzone = "")
ex <- make.index.unique(ex, drop = TRUE, fromLast = TRUE)

但是,生成的xts对象没有唯一索引。我还尝试将strptimeformat="...%OS1"一起使用,它会为所有值返回NA。上面的代码直观地对我没有意义,因为我正在使用输出选项来尝试截断我的日期。

我搜索了其他人如何处理小数时间戳,大多数结果似乎与上述一致。为什么%OS1不适合我,options真的是正确的处理方法吗?我希望我的时间索引在内部以指定的增量截断,每次将options("digits.secs")设置为新的时,我的索引都不会改变。

> options("digits.secs"=3)
> head(ex)
                         V2 V3 V4
2013-04-16 00:00:02.460  NA NA NA
2013-04-16 00:00:02.460 -63  0  1
2013-04-16 00:00:02.463  NA NA NA
2013-04-16 00:00:02.463  NA NA NA
2013-04-16 00:01:09.697  NA NA NA
2013-04-16 00:01:09.697  NA NA NA
> ex <- align.time(ex, n = 0.1)
> head(ex)
                       V2 V3 V4
2013-04-16 00:00:02.5  NA NA NA
2013-04-16 00:00:02.5 -63  0  1
2013-04-16 00:00:02.5  NA NA NA
2013-04-16 00:00:02.5  NA NA NA
2013-04-16 00:01:09.7  NA NA NA
2013-04-16 00:01:09.7  NA NA NA
> ex <- make.index.unique(ex, drop = TRUE, fromLast = TRUE)
> head(ex)
                         V2     V3   V4
2013-04-16 00:00:02.5    NA     NA   NA
2013-04-16 00:01:09.7    NA     NA   NA
2013-04-16 00:01:09.7 -65.5  -7500 0.25
2013-04-16 00:01:13.5 -64.0  -7500 0.25
2013-04-16 00:01:15.4 -64.0 -10000 0.20
2013-04-16 00:01:24.9 -64.0 -10000 0.20

正如您所看到的,我的数据的长度减少了大约三分之一,但即使在前几行中,也有一个重复的时间索引在00:01:09.7。

2 个答案:

答案 0 :(得分:0)

尝试修改您的格式:

strptime(Sys.time(), format = "%Y-%m-%d %H:%M:%S")

'format =“%Y /%m /%d%H:%M:%S”'输出为NA:

strptime(Sys.time(), format = "%Y/%m/%d %H:%M:%S")

答案 1 :(得分:0)

您好像想要汇总数据,而不仅仅是使索引值唯一。假设您要对每列求和,这将有效。如果您不想这样做,只需替换为每列执行所需操作的其他函数。

library(xts)
ex <- structure(c(NA, -63L, NA, NA, NA, NA, NA, 0L, NA, NA, NA, NA, 
NA, 1L, NA, NA, NA, NA), .Dim = c(6L, 3L), .Dimnames = list(NULL, 
    c("V2", "V3", "V4")), index = structure(c(1366088402.46, 
1366088402.46, 1366088402.463, 1366088402.463, 1366088469.697, 
1366088469.697), tzone = "", tclass = c("POSIXct", "POSIXt")),
class = c("xts", "zoo"), .indexCLASS = c("POSIXct", "POSIXt"),
tclass = c("POSIXct", "POSIXt"), .indexTZ = "", tzone = "")

options(digits.secs=6)

# endpoints() doesn't support sub-second resolution on Windows,
# so do what it does using only R code.
ep <- c(0,which(diff(.index(ex)%/%0.1%/%1+1) != 0),NROW(ex))
x <- period.apply(ex, ep, colSums, na.rm=TRUE)
x <- align.time(x, 0.1)