6

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!

bob
  • 610
  • 5
  • 23
  • Makes sense, but I am checking if ANY value in a certain vector is between a pair of dates. Could you help me debug something like this: `between(as.Date('2006-01-01'), as.Date('2006-08-01')) %in% dates`. I would want that to return `TRUE`, for example. – bob Sep 21 '19 at 21:52

3 Answers3

2

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.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
2

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

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) 
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Should it be i1 OR i2? I tried this, and i1 was a vector of length 150 consisting of one/two TRUEs, and i2 also consisted of one/two TRUEs, but `any(i1 & i2)` returned `FALSE` – bob Sep 21 '19 at 21:59
  • @kss I was following your `&` in the code. It cannot be `&` logically – akrun Sep 21 '19 at 22:01
  • I just want it so that if there exists at least one TRUE in i1 AND in i2, then output TRUE, else FALSE. `&` returns FALSE with the example you have given, and `|` returns TRUE as desired, but in the case where i1 contains a TRUE and i2 contains only FALSE, it would still return TRUE overall, which would be wrong. – bob Sep 21 '19 at 22:06
  • @kss In that case you need `any(i1) & any(i2)` updated – akrun Sep 21 '19 at 22:06