2015-09-04 27 views
0

我有3個載體,datesfromDatestoDates。 我怎樣才能提取的fromDates[1]toDates[1]fromDates[2]toDates[2]之間,日期等。從一個載體中提取多個片段R

下面是一個例子。我試圖使用日期[(日期,fromDates,toDates之間]],但結果是不正確的,並有一些警告。

> dates=seq(Sys.Date(),length=1499,by="-1 day") 
> head(dates) 
[1] "2015-09-04" "2015-09-03" "2015-09-02" "2015-09-01" "2015-08-31" "2015-08-30" 
> toDates=seq(Sys.Date()-as.integer(runif(1)*365),length=3,by="-1 year") 
> toDates 
[1] "2015-08-13" "2014-08-13" "2013-08-13" 
> fromDates=toDates-3 
> fromDates 
[1] "2015-08-10" "2014-08-10" "2013-08-10" 
> dates[between(dates,fromDates,toDates)] 
[1] "2015-08-11" "2014-08-12" "2013-08-13" "2013-08-10" 
Warning messages: 
1: In `>=.default`(x, lower) : 
    longer object length is not a multiple of shorter object length 
2: In `<=.default`(x, upper) : 
    longer object length is not a multiple of shorter object length 

如何在不使用循環的情況下提取段?解決方案,其中fromDatestoDates不是矢量,但也可以理解一些其他簡單結構。

謝謝。

+0

請參閱如何使[最小,完整,可驗證的示例](HTTP:/ /stackoverflow.com/help/mcve)或[如何使一個偉大的R可重現的例子](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)。 – N8TRO

+0

在哪個包中包含'between'函數? –

回答

1

沒有太多明確你所要求的,但我會嘗試像你的榜樣如下:

dates[(
    findInterval(dates,c(rbind(rev(fromDates),rev(toDates)))) 
    %% 2) ==1] 
+0

非常感謝。這解決了我的問題。 – sofq