2015-09-13 25 views
0

我有一个数据帧,其看起来像这样改变特定时段

df = data.frame (time = c("2013-12-23 00:00:00", "2013-12-23 00:13:00", "2013-12-23 00:14:00", "2013-12-23 00:14:01", 
          "2013-12-24 00:00:00", "2013-12-24 00:12:00", "2013-12-24 00:15:00", "2013-12-24 00:16:00"), 
       value = c(1, 2, 3, 4, 5, 6, 7, 8)) 

我变换该数据帧到XTS对象,并使用POSIXct格式为索引

df = as.xts(as.numeric(as.character(df[,"value"])), order.by = as.POSIXct(df[,"time"])) 

我现在需要的是更改时间为00:00:00到22:00:00的所有索引。 所有其他时间指数必须保持原样。

最终的目标看起来像这样

>df 
[,1] 
2013-12-23 00:13:00 2 
2013-12-23 00:14:00 3 
2013-12-23 00:14:01 4 
2013-12-23 22:00:00 1 
2013-12-24 00:12:00 6 
2013-12-24 00:15:00 7 
2013-12-24 00:16:00 8 
2013-12-24 22:00:00 5 

感谢您的帮助!帕特

+0

你一定需要改变指数在XTS对象?似乎更容易先修复时间,然后转换为xts对象。 – LyzandeR

+0

不幸的是,我不得不改变xts对象的时间。 – Pat

回答

2

这里是一个函数,将把xts对象的零小时移动n秒。

shiftZeroHour <- function(x, n=1) { 
    stopifnot(is.xts(x)) 
    # find zero hour 
    plt <- as.POSIXlt(index(x), tz=indexTZ(x)) 
    isZeroHour <- plt$hour == 0 & plt$min == 0 & plt$sec == 0 
    # shift zero hour index values 
    .index(x)[isZeroHour] <- .index(x)[isZeroHour] + n 
    # ensure index is ordered properly 
    as.xts(x) 
} 

这里是如何与你的样本数据使用它:

xdf <- structure(c(1, 2, 3, 4, 5, 6, 7, 8), .Dim = c(8L, 1L), 
    index = structure(c(1387778400, 1387779180, 1387779240, 1387779241, 
    1387864800, 1387865520, 1387865700, 1387865760), tzone = "", 
    tclass = c("POSIXct", "POSIXt")), class = c("xts", "zoo"), 
    .indexCLASS = c("POSIXct", "POSIXt"), tclass = c("POSIXct", "POSIXt"), 
    .indexTZ = "", tzone = "") 
shiftZeroHour(xdf, 60*60*22) 
+0

非常有用的乔希!谢谢。也许完整性用xdf代替x在最后一行 – Pat

+0

@Pat:哎呀,修正!谢谢。 –

2

我们可以使用sub更换'00:00:00' 到'22:00:00' 的原始数据集,然后执行xts转换

df$time <- as.POSIXct(sub('00:00:00', '22:00:00', df$time), 
       format='%Y-%m-%d %H:%M:%S') 
library(xts) 
xts(df$value, order.by=df$time) 
#     [,1] 
#2013-12-23 00:13:00 2 
#2013-12-23 00:14:00 3 
#2013-12-23 00:14:01 4 
#2013-12-23 22:00:00 1 
#2013-12-24 00:12:00 6 
#2013-12-24 00:15:00 7 
#2013-12-24 00:16:00 8 
#2013-12-24 22:00:00 5 
+0

谢谢akrun。还有一种方法可以直接替换xts对象中的时间吗?你的回答对我的问题是完美的,但我看到自己面临麻烦,因为我将来不得不再次改变所产生的xts对象。 – Pat

+0

@Pat也许'xts(coredata(df),order.by = as.POSIXct(sub('00:00:00','22:00:00',index(df))))' – akrun

+0

我有那个也是想法。感谢您的帮助,非常感谢。 – Pat