2014-09-21 15 views
0

我想要在POSIXct时间序列的每一天内的时间间隔子集。R帮助在子集与POSIXct的每日范围

假设我有一个3天的样本集,每15分钟抽样一次。

sample <- seq(as.POSIXct("2000-01-01 00:00:00"),as.POSIXct("2000-01-03 24:00:00"),by=15*60) 

[1] "2000-01-01 00:00:00 PST" "2000-01-01 00:15:00 PST" "2000-01-01 00:30:00 PST" "2000-01-01 00:45:00 PST" "2000-01-01 01:00:00 PST" "2000-01-01 01:15:00 PST" "2000-01-01 01:30:00 PST" "2000-01-01 01:45:00 PST" 
[9] "2000-01-01 02:00:00 PST" "2000-01-01 02:15:00 PST" "2000-01-01 02:30:00 PST" "2000-01-01 02:45:00 PST" "2000-01-01 03:00:00 PST" "2000-01-01 03:15:00 PST" "2000-01-01 03:30:00 PST" "2000-01-01 03:45:00 PST" 
[17] "2000-01-01 04:00:00 PST" "2000-01-01 04:15:00 PST" "2000-01-01 04:30:00 PST" "2000-01-01 04:45:00 PST" 

使用lubridate包,我可以相当容易地按小时间隔子集。

sample_subset <- sample[hour(sample) >= 9 & hour(sample) =< 12] 

[1] "2000-01-01 10:00:00 PST" "2000-01-01 10:15:00 PST" "2000-01-01 10:30:00 PST" "2000-01-01 10:45:00 PST" "2000-01-01 11:00:00 PST" "2000-01-01 11:15:00 PST" "2000-01-01 11:30:00 PST" "2000-01-01 11:45:00 PST" 
"2000-01-02 10:00:00 PST" "2000-01-02 10:15:00 PST" "2000-01-02 10:30:00 PST" "2000-01-02 10:45:00 PST" "2000-01-02 11:00:00 PST" "2000-01-02 11:15:00 PST" "2000-01-02 11:30:00 PST" "2000-01-02 11:45:00 PST" 

问题出在如何在每天的固定小时/分钟间隔内进行子集划分。我想每天从9:30到12:00,02:35:40:16:45:45:50,5369,到12:00。如果我只是添加一个过滤器,例如分钟(样本)> 30,则会过滤掉范围内每隔一小时的分钟数。

我看了几个相关的帖子;但他们只显示每小时过滤。似乎应该有一个相当简单的子集条件,我不理解。类似于样本[分钟(样本)[小时(样本)== 9]> 30]但这并不起作用。任何其他简单的想法?

*基于ilister的想法编辑

我简单地扩展与lubridate布尔索引。 我不知何故错过了ORing。

cond1 <- hour(sample) >= 9 & minute(sample) > 30 

cond2 <- hour(sample) < 12 

cond3 <- hour(sample) > 9 

     sample[(cond1 | cond3) & cond2] 

     "2000-01-01 09:45:00 PST" "2000-01-01 10:00:00 PST" "2000-01-01 10:15:00 PST" "2000-01-01 10:30:00 PST" "2000-01-01 10:45:00 PST" 
    "2000-01-01 11:00:00 PST" "2000-01-01 11:15:00 PST" "2000-01-01 
    11:30:00 PST" 

回答

1

尝试子集与indexClass {} XTS共同条件:

require(xts) 
sample <- seq(as.POSIXct("2000-01-01 00:00:00"), 
       as.POSIXct("2000-01-03 24:00:00"),by=15*60) 
xsample <- xts(1:289, order.by=sample) 
xsample[.indexhour(xsample)==9 & .indexmin(xsample) %in% 15:59] 

将在9:15集合返回结果< 10:00。

然后加入标准的.indexhour索引,将设置的10:00返回到12:00。

xsample[c(which(.indexhour(xsample)==9 & .indexmin(xsample) %in% 15:59), 
      which(.indexhour(xsample) %in% 10:11))] 

或者,如果你是舒服布尔运算符,更优雅:

xsample[.indexhour(xsample)==9 & .indexmin(xsample) %in% 15:59 | 
     .indexhour(xsample) %in% 10:11] 
+1

看到的问题了预期的效果,为什么不'xsample [“T09:30: 00/T11:59:59" ]'? – jazzurro 2014-09-21 07:38:38

+0

@jazzurro。更简单!谢谢。 – pat 2014-09-21 08:23:49

0

在基础R,该POSIXlt可能是有用的。尝试:

sampleLT<-as.POSIXlt(sample) 
    secFromMidnigth<-sampleLT$hour*3600+sampleLT$min*60+sampleLT$sec 
    sample[secFromMidnigth>9*3600+30*60 & secFromMidnigth<3600*12] 

可以从一个给定的日期时间的午夜提取的秒数,看看它是否大于更大9 * 3600 + 30 * 60(09:30)和较低的3600 * 12( 12:00)。

我不知道很多的lubridate但我可以从你的OP看你可以做同样的:

sample[hour(sample)*60+minute(sample)>9*60+30 & hour(sample)<12]