2015-09-13 22 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