0

I have 3 vectors, dates, fromDates, and toDates. How can I extract the dates that are between fromDates[1] and toDates[1], fromDates[2] and toDates[2], etc.

Here's an example. I tried to use dates[between(dates,fromDates,toDates)] but the result is incorrect and there are some warnings.

> 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

How can I extract the segments without using a loop? Solution where fromDates and toDates are not vectors but some other simple structures would also be appreciated.

Thanks.

sofq
  • 3
  • 2
  • Please see how to make a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) or [How to make a great R reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – N8TRO Sep 04 '15 at 04:15
  • In which package is `between` function included? – Ronak Shah Sep 04 '15 at 05:22

1 Answers1

1

Not much clear what you are asking, but I'd try something like the following with your example:

dates[(
    findInterval(dates,c(rbind(rev(fromDates),rev(toDates))))
    %% 2) ==1]
nicola
  • 24,005
  • 3
  • 35
  • 56