Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if there exists a value in vector of dates that lies within a given range

I have a vector of dates and want to check for a certain date, whether there exists a value in the vector within the 150 days before it, AND the 150 days before that. A simple example of my data looks like this:

given_date <- as.Date('2006-06-06')
dates <- as.Date(c("2005-02-22", "2005-04-26", "2005-08-02", "2005-10-04", "2005-12-06", "2006-03-14", "2006-06-06"))

I know for a certain date I can do given_date %in% dates, which returns TRUE.

However, for my problem, I want to check something that would look like the following:

ifelse(range(given_date-1, given_date-150) %in% dates & range(given_date-151, given_date-300) %in% dates, TRUE, FALSE)

So for the data I have provided, the result would return TRUE because there exists a date within the 150 days before given_date (e.g. 2006-03-14 exists within the range of (2006-01-07, 2006-06-06)), and another that exists within the 150 days before that (e.g. 2005-10-04 exists within the range of (2005-08-10, 2006-01-07)).

Would appreciate any help regarding how I can do this in R!

like image 460
bob Avatar asked Sep 21 '19 21:09

bob


3 Answers

This checks each of the two conditions and then ANDs them.

any( dates >= given_date - 150 & dates < given_date ) &
  any( dates >= given_date - 300 & dates < given_date - 150 ) 
## [1] TRUE

Update

Fixed.

like image 153
G. Grothendieck Avatar answered Oct 24 '22 13:10

G. Grothendieck


We can use between in dplyr or data.table

library(dplyr)
any(between(dates, given_date - 150, given_date)) && 
   any(between(dates, given_date - 300, given_date - 150))
#[1] TRUE
like image 40
Ronak Shah Avatar answered Oct 24 '22 14:10

Ronak Shah


If we expect only a single TRUE/FALSE as output, then wrap with any after creating a logical vector

i1 <- seq(given_date, length.out = 150, by = "-1 day") %in% dates 
i2 <- seq(given_date - 150, length.out = 150, by = "1 day") %in% dates
any(i1) & any(i2) 
like image 23
akrun Avatar answered Oct 24 '22 13:10

akrun