Ernie
Ernie

Reputation: 1153

Find if a date in a date vector falls between two dates

I have two date vectors, a and b. Vector a has two dates defining a date span. Vector b could have many elements, but I want to know which (if any) element of b falls inside the date span of a. For example,

 a <- c(as.Date("2012-01-01"), as.Date("2012-02-01"))
 b <- c(as.Date("2011-11-09"), as.Date("2012-01-15"), as.Date("2012-5-15"))

Vectors a and b could be zoo/xts objects with numerical values assigned to the dates, or not as required to help with a solution.

The desired answer would be b[2], 2012-01-15. Obviously one can use loops, but there must be a vector solution to this. Help appreciated.

Upvotes: 1

Views: 3392

Answers (2)

Edgar Santos
Edgar Santos

Reputation: 3514

It can be easily done with lubridate e.g.:

library(lubridate)

We first define an interval a:

a <- as.interval(a)

Then using the %within% function we assess if any element of b falls within a:

b[b %within% a]

[1] "2012-01-15"

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 388982

We can also use betweenfrom dplyr. As the name suggests between gives those values which fall in between two values (here a[1] and a[2]).

library(dplyr)
b[between(b, a[1], a[2])]

#[1] "2012-01-15"

Or if we are interested in base R solution, the simplest would be

b[b > a[1] & b < a[2]]

#[1] "2012-01-15"

Upvotes: 3

Related Questions