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!
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
Fixed.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With