将相等的空格时间间隔添加到R

时间:2017-11-22 21:04:13

标签: r data.table xts

很抱歉,如果这是一个相当简单的问题,但我是R和xts以及data.table的新手,我无法在网上找到任何可以帮助我的内容。我的数据类似于以下内容:

    Time                 |   Volume   |   ....
-----------------------------------------------
2005-03-02 11:23:40.111  |    123     |   ....
2005-03-02 11:23:42.675  |    503     |   ....
2005-03-02 11:23:42.749  |    -2      |   ....
2005-03-02 11:23:42.912  |    200     |   ....
2005-03-02 11:23:43.002  |    -76     |   ....
2005-03-02 11:23:43.819  |    -134    |   ....
2005-03-02 11:23:45.353  |    506     |   ....  

我想每秒创建等间隔的时间间隔,以便上表变成下面的新表:

    Time                 |   Volume   |   ....
-----------------------------------------------
2005-03-02 11:23:40      |    123     |   ....
2005-03-02 11:23:41      |    NA      |   ....
2005-03-02 11:23:42      |    701     |   ....
2005-03-02 11:23:43      |    -210    |   ....
2005-03-02 11:23:44      |    NA      |   ....
2005-03-02 11:23:45      |    506     |   ....  

更具体地说,我希望等间隔的秒间隔从09:00开始到每天17:00结束。

这样做有好办法吗?提前致谢

编辑:这是dput输出:

structure(list(HFTtimevec = structure(c(1122855297, 1122855297, 
1122855309, 1122855310.87, 1122855381.82), class = c("POSIXct", 
"POSIXt")), Price = c(3.48, 3.48, 3.48, 21.32, 3.48), Volume = c(2947, 
1398, 920, 4000, 19735)), .Names = c("HFTtimevec", "Price", "Volume"
), row.names = c(NA, -5L), class = c("data.table", "data.frame"
), .internal.selfref = <pointer: 0x0000000002710788>)

1 个答案:

答案 0 :(得分:2)

您需要使用

dat<-data.table(dat)
dat[,Time:=strptime(HFTtimevec, "%Y-%m-%d %H:%M:%OS")]
dat1<-dat[,list(Volume=sum(Volume)),by=list(Time)]

您在此处创建时间变量中的所有数据点:

dt<-data.table(Time=seq(
  ISOdatetime(year=2005, mont=03, day=02, hour=09, min=0, sec=0),
  ISOdatetime(year=2005, mont=03, day=02, hour=17, min=0, sec=0),by="sec"))

newdT<-merge(dt, dat1, by="Time", all.x=T)